繁体   English   中英

将值添加到数组

[英]Adding to values to an array

我有一个数组$products

Array
    (
        [1000] => Array
            (
                [key] => 1000
                [name] => Cat
            )

    )

        [2000] => Array
            (
                [key] => 2000
                [name] => Dog
            )

    )

我通过服务( $extProducts )检索外部数组,我想修改数组( $products ),使其结构如下:

Array
   (
       [1000] => Array
           (
               [key] => 1000
               [name] => Cat
               [ID] => 77
           )

   )

       [2000] => Array
           (
               [key] => 2000
               [name] => Dog
               [ID] => 9

           )

   )

我尝试了以下方法:

foreach ($extProducts as $extProduct){
   $product['ID'] = $extProduct["ID"];
   array_push($products, $product);
}

这只是完全改变了数组,没有给我我需要的东西,任何人都可以帮忙。 - - - - - - - - - - -更新 - -

抱歉,我之前不清楚,外部数组实际上是通过 json 返回的,我将其解码为一个数组。 我不能使用 key 作为$extProducts中的密钥,因为这与$products不匹配。

还有nb。
$extProduct["ID"]; 实际上是$extProduct["Data"]["context"]["UpdatedOrder"]["Items"]["ID"];

{
    "Success": true,
    "StatusCode": 200,
    "StatusDesc": "Success",
    "Data": {
        "context": {
            "$id": "1",
            "UpdatedOrder": {
                "$id": "2",
                },
                "Items": [
                    {
                        "ID": "4",
                        "Price": 6.99,
                    },
                    {
                        "ID": "7",
                        "Price": 1.39,
                    }
                ],
            "ApiResult": {
                "$id": "9",
                "TransactionId": "xxx",
                "ResultCode": 0,
                "ResultMessage": "Success"
            }
        }
    }
}

谢谢

foreach ($extProducts as $id=>$extProduct){
   $extProducts[$id]["ID"]=123; //reference your ID here
}

希望这可以帮助。

试试这个:

foreach($products as $key => $product){

  foreach($key as $mod_product){
     $mod_product['ID'] = $extProduct["ID"];
     array_push($products, $mod_product);


 }

}

从 JSON 数组中获取项目 ID:-

 $itemID = array();
 foreach($extProduct["Data"]["context"]["Items"] as 
 $itemId) {
        array_push($itemID,$itemId["ID"];
 }

现在格式化您的结果数组:-

  $resultArray = Array();
  $i = 0;

  foreach($products as $product){

      foreach($product as $key => $mod_product){

          array_push($mod_product,$itemID[$i]);
          array_push($resultArray,$mod_product);
          $i++;

       }

    }

试试这个答案。 我想,你会得到想要的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM