我有以下数组(从数据库中检索的内容):
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)
我需要按如下方式创建一个数组:
$info = array('one' => 'Billy', 'two' => 'Mariah', 'three' => 'Cindy', 'four' => 'Daniel');
我使用了foreach循环来构造所需的数组:
$info = array();
foreach ($result as $row) {
$info[] = array($row['number'] => $row['name']);
}
和var_dump()给了我这个:
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)
如何在PHP中实现所需的数组?感谢您的帮助。
答案 0 :(得分:5)
你很亲密。
$info = array();
foreach ($result as $row) {
$info[$row['number']] =$row['name'];
}
答案 1 :(得分:0)
使用PHP> = 5.5.0,它更容易:
$info = array_column($result, 'name', 'number');