有时我们需要遍历一个数组并对索引进行分组,以便在迭代中更容易提取它们。
<?php
$people = [
['id' => 1, 'name' => 'Hayley'],
['id' => 2, 'name' => 'Jack', 'dad' => 1],
['id' => 3, 'name' => 'Linus', 'dad'=> 4],
['id' => 4, 'name' => 'Peter' ],
['id' => 5, 'name' => 'Tom', 'dad' => 4],
];
$family = array_reduce($people, function($accumulator, $item) {
if (!isset($item['dad'])) {
$id = $item['id'];
$name = $item['name'];
$children = $accumulator[$id]['children'] ?? [];
$accumulator[$id] = ['id' => $id, 'name' => $name,'children' => $children];
return $accumulator;
}
$dad = $item['dad'];
if (!isset($accumulator[$dad])) {
$accumulator[$dad] = ['children' => [$item]];
return $accumulator;
}
$accumulator[$dad]['children'][] = $item;
return $accumulator;
}, []);
var_export(array_values($family));
?>
输出
array (
0 =>
array (
'id' => 1,
'name' => 'Hayley',
'children' =>
array (
0 =>
array (
'id' => 2,
'name' => 'Jack',
'dad' => 1,
),
),
),
1 =>
array (
'id' => 4,
'name' => 'Peter',
'children' =>
array (
0 =>
array (
'id' => 3,
'name' => 'Linus',
'dad' => 4,
),
1 =>
array (
'id' => 5,
'name' => 'Tom',
'dad' => 4,
),
),
),
)
<?php
$array = [
[
"menu_id" => "1",
"menu_name" => "Clients",
"submenu_name" => "Add",
"submenu_link" => "clients/add"
],
[
"menu_id" => "1",
"menu_name" => "Clients",
"submenu_name" => "List",
"submenu_link" => "clients"
],
[
"menu_id" => "2",
"menu_name" => "Products",
"submenu_name" => "List",
"submenu_link" => "products"
],
];
$menu = array_reduce($array, function($accumulator, $item){
$index = $item['menu_name'];
if (!isset($accumulator[$index])) {
$accumulator[$index] = [
'menu_id' => $item['menu_id'],
'menu_name' => $item['menu_name'],
'submenu' => []
];
}
$accumulator[$index]['submenu'][] = [
'submenu_name' => $item['submenu_name'],
'submenu_link' => $item['submenu_link']
];
return $accumulator;
}, []);
var_export(array_values($menu));
?>
输出
array (
0 =>
array (
'menu_id' => '1',
'menu_name' => 'Clients',
'submenu' =>
array (
0 =>
array (
'submenu_name' => 'Add',
'submenu_link' => 'clients/add',
),
1 =>
array (
'submenu_name' => 'List',
'submenu_link' => 'clients',
),
),
),
1 =>
array (
'menu_id' => '2',
'menu_name' => 'Products',
'submenu' =>
array (
0 =>
array (
'submenu_name' => 'List',
'submenu_link' => 'products',
),
),
),
)