有一些小伙伴,对于array_column 的使用不是很熟悉,只会用于提取二维数组的某个字段一种用法。实际有很多种常见用法。
比如:有一个数组:
$arr = [
['id' => "5", 'name' => 'D', 'age' => 18],
['id' => "1", 'name' => 'A', 'age' => 19],
['id' => "2", 'name' => 'B', 'age' => 20],
['id' => "3", 'name' => 'C', 'age' => 18],
];
1. 将数组的id抽取出来,组成一个新的一维数组:
$newArr = array_column($arr,'id');
// 输出
Array
(
[0] => 5
[1] => 1
[2] => 2
[3] => 3
)
2. 将id作为key,name作为value,组成一个新的一维数组:
$newArr = array_column($arr,'name','id');
// 输出
Array
(
[5] => D
[1] => A
[2] => B
[3] => C
)
3. 将id作为二维树数组的key,替换掉原来的默认有序key
$newArr = array_column($arr, null,'id');
// 输出
Array
(
[5] => Array
(
[id] => 5
[name] => D
[age] => 18
)
[1] => Array
(
[id] => 1
[name] => A
[age] => 19
)
[2] => Array
(
[id] => 2
[name] => B
[age] => 20
)
[3] => Array
(
[id] => 3
[name] => C
[age] => 18
)
)
4. 将二维数组的id值的大小作为排序条件进行排序:
$fields = array_column($arr, 'id');
array_multisort($fields, SORT_ASC, $arr);
// 输出:
Array
(
[0] => Array
(
[id] => 1
[name] => A
[age] => 19
)
[1] => Array
(
[id] => 2
[name] => B
[age] => 20
)
[2] => Array
(
[id] => 3
[name] => C
[age] => 18
)
[3] => Array
(
[id] => 5
[name] => D
[age] => 18
)
)