二维数组转一维数组的几个方法


$arr = [
    [
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    [
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ],
    [
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ],
    [
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    ]
];

/**
 * 1.使用array_column()函数,要求php版本5.5+
 * array_column()返回数组中某一列的值
 * array_column(array,column_key,index_key);
 */
var_dump(array_column($arr,'first_name'));

/**
 * 2.array_walk()函数使用用户自定义函数对数组中的每个元素做回调处理
 */
$first_names = [];
array_walk($arr, function ($value, $key) use (&$first_names) {
     
    $first_names[] = $value['first_name'];
});
var_dump($first_names);

/**
 * 3.array_map()函数和array_walk()作用类似,将回调函数作用到给定数组的单元上
 */

$first_names = [];
array_map(function ($value) use (&$first_names) {
     
    $first_names[] = $value['first_name'];
},$arr);
var_dump($first_names);

/**
 * 4.array_reduce()用回调函数迭代地将数组简化为单一的值
 */
$first_names = array_reduce($arr,function ($result, $value) {
     
    array_push($result, $value['first_name']);
    return $result;
},[]);
var_dump($first_names);
array(4) {
  [0]=>
  string(4) "John"
  [1]=>
  string(5) "Sally"
  [2]=>
  string(4) "Jane"
  [3]=>
  string(5) "Peter"
}
array(4) {
  [0]=>
  string(4) "John"
  [1]=>
  string(5) "Sally"
  [2]=>
  string(4) "Jane"
  [3]=>
  string(5) "Peter"
}
array(4) {
  [0]=>
  string(4) "John"
  [1]=>
  string(5) "Sally"
  [2]=>
  string(4) "Jane"
  [3]=>
  string(5) "Peter"
}
array(4) {
  [0]=>
  string(4) "John"
  [1]=>
  string(5) "Sally"
  [2]=>
  string(4) "Jane"
  [3]=>
  string(5) "Peter"
}

参考文章链接:
https://www.cnblogs.com/honeyJYY/p/10430716.html
https://blog.csdn.net/lengyuezuixue/article/details/86552664
https://www.runoob.com/php/func-array-column.html

你可能感兴趣的:(PHP,php,数组)