I want to populate option tags from my array:
JavaScript
x
$array = [
[
"id" => "64",
"name" => "Freddy",
"firstname" => "Lang"
],
[
"id" => "77",
"name" => "Samual",
"firstname" => "Johnson"
]
];
I tried with:
JavaScript
$id = array_column($array, 'id');
$firstname = array_column($array, 'firstname');
$name = array_column($array, 'name');
echo "<select>";
echo implode('<option value ="'.$id.'"'>'.$firstname.' '.$name.'</option>);
echo "</select>";
But I get a blank page as result.
I expect:
JavaScript
<option "64">Freddy Lang</option>
<option "77">Samual Johnson</option>
Advertisement
Answer
You could use array_map
to transform the input array into the html code for a <option>
then implode
all, using only one statement:
JavaScript
echo "<select>" . implode('', array_map(function($row) {
return '<option value="'.$row['id'].'">'. $row['firstname'] .' '. $row['name'].'</option>';
}, $array )) . "</select>";