【发布时间】:2016-08-01 05:21:17
【问题描述】:
我在多级数组中有以下数据
1: id: 41, parent: null, name: lucas
2: id: 52, parent: null, name: george
3: id 98: parent: 41, name: julian
...
我需要遍历这个数组和一个'childrens' 键和值到父级,同时每次我运行一个“父级”未设置为空的条目时对该值求和+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 添加到第一个孩子而不是父母。
为什么?
【问题讨论】:
-
这个
$idPai是从哪里来的? -
对不起@Saurabh,它应该是$idParent,我在发布之前翻译了变量名称并忘记了这个。编辑:固定
-
要删除通知,在包含 increment 的行之前添加
if( !isset($post[$idParent]['childrens']) ) { $post[$idParent]['childrens']=0; }。 -
谢谢@olegsv。你知道是否有可能做我想做的事吗?我不明白为什么我的代码不起作用。如果我 echo $idChild has $idParent as a parent 有效,为什么 $post[$idParent]["children"]++ 不起作用?
-
我在 2010 年为此编写了一个实现:stackoverflow.com/questions/3261228/…