二维数组转一维数组总结
例如将如下二位数组转以为以为一维数组
$records = [ [ ‘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()
array_column()是PHP内置函数,限制是PHP版本必须是5.5.0及以上版本!
<?php $first_names = array_column($records, ‘first_name‘); var_dump($first_names); ?>
打印结果为:$first_names = [‘John‘,‘Sally‘,‘Jane‘,‘Peter‘];
<?php $first_names = array_column($records, ‘first_name‘,‘id‘); var_dump($first_names); ?>打印结果为:$first_names = [2135 =>‘John‘,3245 => ‘Sally‘,5342 => ‘Jane‘,5623 => ‘Peter‘];
2.array_walk()
array_walk()函数使用用户自定义函数对数组中的每个元素做回调处理,实现当前功能的方法:
$first_names= []; array_walk($records, function($value, $key) use (&$first_names){ $first_names[] = $value[‘first_name‘]; });var_dump($first_names);
打印结果为:$first_names = [‘John‘,‘Sally‘,‘Jane‘,‘Peter‘];
3.array_map()
array_map()函数和array_walk() 作用类似,将回调函数作用到给定数组的单元上。
$first_names= []; array_map(function($value) use (&$first_names){ $first_names[] = $value[‘first_name‘]; }, $records);
var_dump($first_names);
打印结果为:$first_names = [‘John‘,‘Sally‘,‘Jane‘,‘Peter‘];
4.array_reduce()
array_reduce — 用回调函数迭代地将数组简化为单一的值。
原文地址:https://www.cnblogs.com/honeyJYY/p/10430716.html
时间: 2024-10-28 09:20:42