PHP:将键值添加到现有键的值=>值数组

时间:2017-01-17 22:28:45

标签: php arrays

我有一个像这样结构的数组:

data: [
    {
       "category": "CAT555",
       "products": {
           "productID": 12345,
           "sku": 3333
       },
    },
    {
      "category": "CAT1111",
      "products": {
          "productID: 12441,
          "sku": 9999
      },
   }
]

如果我有新产品,我想添加到CAT555类别?我该怎么做?

目前有这个:

$key = array_search($categoryID, array_column($categories, 'categoryID'));

 if ($key != false){
    $categories[$key]['products'][] = [
       'productID': '91232',
       'sku': '52433'
    ];

但结果最终看起来像这样:

data: [
    {
       "category": "CAT555",
       "products": 
       "0": {
            "productID": 12345,
            "sku": 3333
            }
       },
       {
           "productID": 12345,
           "sku": 3333
       },
    },
    {
      "category": "CAT1111",
      "products": {
          "productID: 12441,
          "sku": 9999
      },
   }
]

1 个答案:

答案 0 :(得分:0)

array_merge函数使用以下方法:

$new_product = [
    'productID' => '91232',
    'sku' => '52433'
 ];
$search_key = 'CAT555';
foreach ($categories as $k => &$v) {
    if ($v['category'] == $search_key) {  // if the needed key is found
        (isset($v['products'][0]))? 
            $v['products'].push($new_product) 
            : $v['products'] = array_merge([$v['products']], [$new_product]);
    }
}

print_r($categories);