basket.json

[ { "item": 13 }, { "item": 12 } ] 

code:

 $posted_value = 13; $basketJson = file_get_contents('basket.json'); $usedBasket = json_decode($basketJson, true); foreach ( $usedBasket as $basket ) { foreach ( $basket as $key => $value ) { if (( $key = array_search($posted_value, $value)) !== false ) { unset($basket[$key]); } } } file_put_contents('basket.json', json_encode($usedBasket)); 

but the object also has a value of 13. What is wrong?

    2 answers 2

    In foreach, the default is a copy of the array. To gain access to the source array, you need to add an ampersand in both cycles:

     foreach ($usedBasket as &$basket) 

    and

     foreach ($basket as $key => &$value) 

    If you change only $ basket, then you can not add an ampersand in the second cycle.


    To modify the array, it would be more convenient to use for () instead of foreach (), if only because it would not delete the remaining links after the cycle. For example:

     $posted_value = 13; $basketJson = '[ { "item": 13 }, { "item": 12 } ]'; $usedBasket = json_decode($basketJson, true); for ($i = 0, $all = count($usedBasket); $i < $all; $i++) { if ($usedBasket[$i]['item'] === $posted_value) { unset($usedBasket[$i]); } } $usedBasket = array_values($usedBasket); var_dump($usedBasket); 

    Result:

     array(1) { [0]=> array(1) { ["item"]=> int(12) } } 
    • For some reason, there was an empty array [[], {"item": 12}], I counted on [{"item": 12}], how to improve it? - GarfieldCat
    • now {"1": {"item": 12}} "1" ... it feels like you need to re-index the array somehow. - GarfieldCat
    • @GarfieldCat added the answer. - Edward
     $posted_value = 13; $basketJson = file_get_contents('basket.json'); $usedBasket = json_decode($basketJson, true); if(($key = array_search($posted_value, array_column($usedBasket, 'item'))) !== false) { // Удаление элемента. // unset($usedBasket[$key]); // Удаление с переиндексацией. array_splice($usedBasket, $key, 1); } file_put_contents('basket.json', json_encode($usedBasket));