很多情況下,我們數據庫是以二維數據存儲的,但是我們查出來以后,需要轉成一維數組,PHP有這么一個函數array_column,能實現大部分的 二維數組轉一維數組
//PHP版本>= 5.5//PHP二維數組降一維函數$student= array(
array('no'=> 301,'name'=>'zhangsan','score'=>'60'),array('no'=> 302,'name'=>'zhaoliu','score'=>'98'),array('no'=> 305,'name'=>'lisi','score'=>'92'),array('no'=> 308,'name'=>'wangwu','score'=>'71'),array('no'=> 325,'name'=>'zhzousa','score'=>'80'),);
1.更改某列為二維數組的索引
$arr1= array_column($student,null,'no');print_r($arr1);
打印結果:
Array
(
[301] => Array
(
[no] => 301
[name] => zhangsan
[score] => 60
)
[302] => Array
(
[no] => 302
[name] => zhaoliu
[score] => 98
)
[305] => Array
(
[no] => 305
[name] => lisi
[score] => 92
)
[308] => Array
(
[no] => 308
[name] => wangwu
[score] => 71
)
[325] => Array
(
[no] => 325
[name] => zhzousa
[score] => 80
)
)
2. 取其中一列組成新的一維數組
$arr2= array_column($student,'no');print_r($arr2);打印結果:
Array
(
[0] => 301
[1] => 302
[2] => 305
[3] => 308
[4] => 325
)
3. 二維數組中的倆列分別作為鍵和值
注意:參數分別是(二維數組,作為值的列名,作為鍵的列名)
$arr3= array_column($student,'name','no');print_r($arr3);打印結果:
Array
(
[301] => zhangsan
[302] => zhaoliu
[305] => lisi
[308] => wangwu
[325] => zhzousa
)