简体   繁体   中英

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. 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.

here is the json array snippet in result/

"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.

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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