今天想统计二维数组中某个字段相同的个数,思路清晰一下就明白了,直接上代码:
一、原始方式:
二维数组:
$data = [ ['id' => 1, 'name' => 'John', 'age' => 25], ['id' => 2, 'name' => 'Jane', 'age' => 30], ['id' => 3, 'name' => 'John', 'age' => 28], ['id' => 4, 'name' => 'Jane', 'age' => 35], ['id' => 5, 'name' => 'John', 'age' => 25],];
创建一个空数组用于存储统计结果:
$statistics = [];
遍历二维数组进行统计:
foreach ($data as $item) { // 获取当前元素的两个属性值 $name = $item['name'];$age = $item['age']; // 以两个属性值作为键,将数据进行分组 注意:这里是关键,就一段代码改变所有 $key = $name . '_' . $age; if (!isset($statistics[$key])) { $statistics[$key] = []; } $statistics[$key][] = $item;}
输出统计结果:
foreach ($statistics as $key => $group) { echo "属性相同的数据({$key})有:" . PHP_EOL; foreach ($group as $item) { echo "ID: {$item['id']}, Name: {$item['name']}, Age: {$item['age']}" . PHP_EOL; } echo PHP_EOL;}
运行结果:
属性相同的数据(John_25)有:ID: 1, Name: John, Age: 25ID: 5, Name: John, Age: 25
属性相同的数据(Jane_30)有:ID: 2, Name: Jane, Age: 30
属性相同的数据(John_28)有:ID: 3, Name: John, Age: 28
属性相同的数据(Jane_35)有:ID: 4, Name: Jane, Age: 35
二、函数方式:
$data = [ ['id' => 1, 'name' => 'John', 'age' => 25], ['id' => 2, 'name' => 'Jane', 'age' => 30], ['id' => 3, 'name' => 'John', 'age' => 28], ['id' => 4, 'name' => 'Jane', 'age' => 35], ['id' => 5, 'name' => 'John', 'age' => 25],];
$statistics = [];
array_map(function ($v) use(&$statistics){ $key = $v['name'] . '_' . $v['age']; if (!isset($statistics[$key])) { $statistics[$key] = []; } $statistics[$key][] = $v;},$data);
array_walk($statistics,function ($group,$key){ echo "属性相同的数据({$key})有:" . PHP_EOL; foreach ($group as $item) { echo "ID: {$item['id']}, Name: {$item['name']}, Age: {$item['age']}" . PHP_EOL; } echo PHP_EOL;});
运行结果:
属性相同的数据(John_25)有:ID: 1, Name: John, Age: 25ID: 5, Name: John, Age: 25
属性相同的数据(Jane_30)有:ID: 2, Name: Jane, Age: 30
属性相同的数据(John_28)有:ID: 3, Name: John, Age: 28
属性相同的数据(Jane_35)有:ID: 4, Name: Jane, Age: 35
领取专属 10元无门槛券
私享最新 技术干货