Reputation: 485
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.
Upvotes: 2
Views: 5445
Reputation: 7896
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"
}]
Upvotes: 4