Home > Enterprise >  Creating Array with variable
Creating Array with variable

Time:01-09

how can i create array with a variable ? example:

$id=1;
$query=$db->prepare("SELECT * FROM number_table WHERE scheme_id='61d4359c6a205'");
$query->execute();
while ($exe=$query->fetch(PDO::FETCH_ASSOC)) { $id  ; 
                                                                        
    $numbers .= '"'.$exe['number_id'].'"=>"'.$exe['number_value'].'", ';
                                                    
}

echo $numbers; //output "2090"=>"15", "1501=>"16", "4561"=>"17", "6287"=>"12",

$arr_numbers = array($numbers);
print_r($arr_numbers); // output Array ( [0] => "2090"=>"15", "1501"=>"16", "4561"=>"17", "6287"=>"17",)  that output is not what i want.

I want to do something like that. But my code is does not work.

CodePudding user response:

Creating an array from a string no matter the format, it will create a single-element array with that string array('[0] => "test"') ==> [0] => '[0] => "test"'

Try creating the array during the loop, you don't need anything else :

while ($exe=$query->fetch(PDO::FETCH_ASSOC)) { $id  ;                                                                         
    $arr_numbers[$exe['number_id']]=$exe['number_value'];                                                 
}
print_r($arr_numbers); 
  •  Tags:  
  • Related