美文网首页
两个二维数组父子多对多关联

两个二维数组父子多对多关联

作者: dongdog | 来源:发表于2020-06-15 14:53 被阅读0次
    /**
     * 父子数组组装多对多
     *
     * @param array  $arr1     父数组
     * @param array  $arr2     子数组
     * @param string $arr1_key 数组1对应的键值
     * @param string $arr2_key 数组2对应的父级键值
     * @param string $child    父子关联键名
     *
     * @return mixed
     */
    static function fatherSonManyToMany($arr1, $arr2, $arr1_key = 'id', $arr2_key = 'pid', $child = 'children')
    {
        //父级
        foreach ($arr1 as $i => $item1) {
            //子级
            foreach ($arr2 as $j => $item2) {
                //父级与子级匹配
                if ($item1[$arr1_key] == $item2[$arr2_key]) {
                    //去除子级关联ID
                    unset($item2[$arr2_key]);
                    $arr1[$i][$child][] = $item2;
                }
            }
            //          unset($arr1[$i][$arr1_key]);
        }
        return $arr1;
    }

    相关文章

      网友评论

          本文标题:两个二维数组父子多对多关联

          本文链接:https://www.haomeiwen.com/subject/gpacxktx.html