Reputation: 611
How do I create an array of SQL fetched results and sort by keys that are taken from the results themselves?
For example, here is how the results from the database look like:
$results = array(
[0] => array(
'id' => 'cat',
'name' => 'Kitty'
),
[1] => array(
'id' => 'dog',
'name' => 'Rex'
)
);
I want to turn into:
$results = array(
['cat'] => array(
'id' => 'cat',
'name' => 'Kitty'
),
['dog'] => array(
'id' => 'dog',
'name' => 'Rex'
)
);
I can do it with a foreach
loop, but is there a built-in function that I'm missing?
Upvotes: 1
Views: 37
Reputation: 7703
Yes, the function array_column does exactly what you want.
$results = array(
array('id' => 'cat', 'name' => 'Kitty'),
array('id' => 'dog', 'name' => 'Rex')
);
$res = array_column($results,null,'id');
echo "<pre>";
var_export($res);
Output:
array (
'cat' =>
array (
'id' => 'cat',
'name' => 'Kitty',
),
'dog' =>
array (
'id' => 'dog',
'name' => 'Rex',
),
)
Upvotes: 1