I have the following array (contents retrieved from a DB):
array (size=4)
0 =>
array (size=2)
'number' => string 'one' (length=3)
'name' => string 'Billy' (length=5)
1 =>
array (size=2)
'number' => string 'two' (length=3)
'name' => string 'Mariah' (length=6)
2 =>
array (size=2)
'number' => string 'three' (length=5)
'name' => string 'Cindy' (length=5)
3 =>
array (size=2)
'number' => string 'four' (length=4)
'name' => string 'Daniel' (length=6)
I need to create an array as follows:
$info = array('one' => 'Billy', 'two' => 'Mariah', 'three' => 'Cindy', 'four' => 'Daniel');
I used a foreach loop to construct the desired array:
$info = array();
foreach ($result as $row) {
$info[] = array($row['number'] => $row['name']);
}
and a var_dump() gives me this instead:
array (size=4)
0 =>
array (size=1)
'one' => string 'Billy' (length=5)
1 =>
array (size=1)
'two' => string 'Mariah' (length=6)
2 =>
array (size=1)
'three' => string 'Cindy' (length=5)
3 =>
array (size=1)
'four' => string 'Daniel' (length=6)
How can I achieve the desired array in PHP? Thanks for your help in advance.
You were close.
$info = array();
foreach ($result as $row) {
$info[$row['number']] =$row['name'];
}
With PHP >= 5.5.0 it's much easier:
$info = array_column($result, 'name', 'number');
Or use the PHP Implementation of array_column()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.