2

I have a json array

[{
    "sku": "5221",
    "qty": 1,
    "price": 17.5,
    "desc": "5395 - Replenish Natural Hydrating Lotion 3.5oz"
}, {
    "sku": "11004",
    "qty": 1,
    "price": 30.95,
    "desc": "150 - Q-Plus 16oz"
}]

i am getting this array inside $item php variable and decoding that array

$jsonDecode = json_decode($items, true);
echo 'before' . PHP_EOL;
print_r($jsonDecode);

foreach ($jsonDecode as $key => $obj) {
    if ($obj->sku == '11004') {
        $jsonDecode[$key]['qty'] = '5';
    }
}
print_r($jsonDecode);

now i want if sku is 11004 then qty of that index would be 5 . but after using above code i got same array with same qty for that index.

how can i do so Please Help.

3
  • your json string doesn't seem to be valid. show the full json string Commented Apr 14, 2016 at 8:24
  • you want to update the quantity and then create new json? Commented Apr 14, 2016 at 8:26
  • yes @ChetanAmeta i want to update qty of same json with 11004 sku and then want to save in DB. i am print json decoded array two time 1st before implementing foreach and 2nd after implementing foreach but getting same array without any change Commented Apr 14, 2016 at 8:36

1 Answer 1

4

try below solution:

$json = '[{
    "sku": "5221",
    "qty": 1,
    "price": 17.5,
    "desc": "5395 - Replenish Natural Hydrating Lotion 3.5oz"
}, {
    "sku": "11004",
    "qty": 1,
    "price": 30.95,
    "desc": "150 - Q-Plus 16oz"
}]';

$array = json_decode($json, true);
//print_r($array);

foreach($array as &$a){
    if($a['sku'] == 11004){
        $a['qty'] = 5;
    }
}

echo json_encode($array);

output:

[{
    "sku": "5221",
    "qty": 1,
    "price": 17.5,
    "desc": "5395 - Replenish Natural Hydrating Lotion 3.5oz"
}, {
    "sku": "11004",
    "qty": 5,
    "price": 30.95,
    "desc": "150 - Q-Plus 16oz"
}]
Sign up to request clarification or add additional context in comments.

5 Comments

Tried but still getting same array without any qty change.
have you used & with val in foreach loop .... working fine for me.. have a look at 3v4l.org/1IBIO
Worked dude thanks , but can you please tell me why we are using & here?
@KaranAdhikari -> By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference. To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition. link
Thank you @ShriSuresh for clarification i really appreciate this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.