我在多级arrarray中有以下数据
1: id: 41, parent: null, name: lucas
2: id: 52, parent: null, name: george
3: id 98: parent: 41, name: julian
...
我需要循环遍历此数组并将'childrens'
键和值循环到父级,同时每次运行“父级”未设置为null的条目时,将+1加到此值。怎么做到这一点?
1: id: 41, parent: null, name: lucas, children: 1
我在foreach
foreach($post as $parsedPost) {
if($parsedPost['parent'] > 0){
$idChild = $parsedPost['id'];
$idParent = $parsedPost['parent'];
$post[$idParent]["childrens"]++;
}
}
当然,它会返回一个通知,因为索引['childrens']
不存在。此外,它将childrens:value
添加到第一个孩子而不是父母。
为什么呢?
答案 0 :(得分:1)
希望这有帮助。
$post[] = ["id" => "41", "parent" => null, "name" => "lucas"];
$post[] = ["id" => "52", "parent" => null, "name" => "george"];
$post[] = ["id" => "98", "parent" => "41", "name" => "Julian"];
foreach ($post as $parsedPost)
{
if ($parsedPost['parent'] > 0 && $parsedPost['parent'] != "")
{
$idChild = $parsedPost['id'];
$idParent = $parsedPost['parent'];
$parentKey = array_search($idParent,array_column($post,'id'));
if(!isset($post[$parentKey]["childrens"]))
{
$post[$parentKey]["childrens"] = 0;
}
$post[$parentKey]["childrens"]++;
}
}
print_r($post);
输出:
Array
(
[0] => Array
(
[id] => 41
[parent] =>
[name] => lucas
[childrens] => 1
)
[1] => Array
(
[id] => 52
[parent] =>
[name] => george
)
[2] => Array
(
[id] => 98
[parent] => 41
[name] => Julian
)
)