循环遍历数组,同时根据另一个值添加新键:值对

时间:2016-08-01 05:21:18

标签: php arrays foreach

我在多级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添加到第一个孩子而不是父母。 为什么呢?

1 个答案:

答案 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
        )

)