简体   繁体   English

php查看json数组修改特殊值并返回数组

[英]Php look through json array modify a special value and return the array

So I have a JSON array with some content in the array.所以我有一个 JSON 数组,数组中有一些内容。 each item has product id and price, my aim is to loop through this array, and modify the product price and return array with modified product price.每个项目都有产品 id 和价格,我的目的是循环遍历这个数组,并修改产品价格并使用修改后的产品价格返回数组。

here is the json array snippet in result/这是结果/中的json数组片段

"variation_combination_price" => array:4 [▼
0 => array:10 [▼
  "id" => 1
  "product_id" => 1364
  "cost_price" => 600
  "promo_price" => 900
  "price" => 900
  "combination_array" => array:2 [▼
    0 => array:8 [▶]
    1 => array:8 [▶]
  ]
  "combination_array_string" => "{"1":"3","2":"4"}"
  "quantity" => 10000
  "status" => 1
  "DOCUMENTATION" => array:2 [▶]
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]

So the result above is the original response.所以上面的结果是原始响应。 As you can see we have 4 items there, the aim is to loop though them, modify the price and return same 4 items.如您所见,我们有 4 个项目,目的是遍历它们,修改价格并返回相同的 4 个项目。

  foreach ($product_data['variation_combination_price'] as  
  $variation_combination_price){

        $variation_combination_price['price'] = 666;

        $product_data['variation_combination_price'] = 
$variation_combination_price;

    }


    dd($product_data['variation_combination_price']);  

My result should come with the same array where price is modified.我的结果应该与修改价格的数组相同。

"variation_combination_price" => array:4 [▼
0 => array:10 [▼
  "id" => 1
  "product_id" => 1364
  "cost_price" => 600
  "promo_price" => 900
  "price" => 666
  "combination_array" => array:2 [▼
    0 => array:8 [▶]
    1 => array:8 [▶]
  ]
  "combination_array_string" => "{"1":"3","2":"4"}"
  "quantity" => 10000
  "status" => 1
  "DOCUMENTATION" => array:2 [▶]
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]

You are not looping by reference.你不是通过引用循环。
Whatever changes you do in the loop will not change the value of the array.您在循环中所做的任何更改都不会更改数组的值。
In order to do so you need to add a &为此,您需要添加一个&

foreach ($product_data['variation_combination_price'] as &$variation_combination_price){
    $variation_combination_price['price'] = 666;
}

Just remember to unset the variable after the loop also.只记得在循环之后取消设置变量。

unset($variation_combination_price);

To make sure you don't change the array data after the loop is done.确保在循环完成后不更改数组数据。

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

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