【问题标题】:Loop through an array while adding a new key:value pair based on another value循环遍历一个数组,同时添加一个基于另一个值的新键:值对
【发布时间】: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/…

标签: php arrays foreach


【解决方案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
        )

)

【讨论】:

  • 您的代码确实有效,谢谢!但是对于每个有孩子的条目,它会跳过 1 个孩子。你知道为什么吗?
  • 我没听懂你能详细解释一下吗?
  • Entry 1 on my database has 6 childrens and your script calculates 6 childrens.Entry 2 on my database has 3 childrens and your script calculates 2 childrens. 我要为这个发疯了 :D 很高兴你能帮忙
  • 我为 id 52 添加了 3 个孩子,它显示了 3 个孩子。
  • @LucasRabelloSimões 你可以在这里发布 SQL 表吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2014-11-17
  • 2020-12-22
  • 1970-01-01
相关资源
最近更新 更多