php 数组合并的问题

迷ss
  • 2
新手上路,请多包涵

现在有两个数组结构如下:
clist店铺的数组,list是商品的数组,
商品中的goods_shops_id和店铺中的id相当

想和并的效果是一个店铺包含该店铺的多个商品
试了好多方法都没成功,还请大神赐教~~~~
`"clist":[
            {
                "id":1,
                "store_name":"店铺一",
              
            },
            {
                "id":4,
                "store_name":"店铺二",
               
            }
        ]`

    
    商品数据list:
    

"list":[
            {
                "id":8719,
                "user_id":1,
                "product_id":869,
                
                "goods_shops_id":1,
                
                },
                
                
            },
            {
                "id":8723,
                
                "goods_shops_id":1,
                "weight":"500.00",
                
            },
            {
                "id":8725,
                
                "product_id":902,
                
                "goods_shops_id":4,
              
            }
        ]

回复
阅读 964
3 个回答

两层循环,判断下clist下的 id 等于list下的goods_shops_id时,就将当前 list 下这个 val 数据放入 clist 下的一个 key 里就好了

迷ss
  • 2
新手上路,请多包涵

我是这么做的,但是$label_ids[$item]['goods_list'][] = $m;这句报错了
$new_arr = [];


foreach ($label_ids as $item => $value) {
    foreach ($result['data']['list'] as $n => $m) {
        if ($label_ids[$item]['id'] == $result['data']['list'][$n]['goods_shops_id']) {
$label_ids[$item]['goods_list'][] = $m; //类的属性不存在 
            $new_arr = $label_ids;
        }
    }
}

属性不存在,需要先创建哈。

foreach ($label_ids as $item => $value) {
    foreach ($result['data']['list'] as $n => $m) {
        if ($label_ids[$item]['id'] == $result['data']['list'][$n]['goods_shops_id']) {
            if (!isset($label_ids[$item]['goods_list'])){
                $label_ids[$item]['goods_list'] = array();
            }
            $label_ids[$item]['goods_list'][] = $m; //类的属性不存在 
            $new_arr = $label_ids;
        }
    }
}

可以关注下我的公众号: 搬砖程序员带你飞 各种学习干货

你知道吗?

宣传栏