我有一个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"
}]
我在$ item php变量中获取此数组并解码该数组
$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);
现在我想如果sku是11004那么该指数的数量将是5。 但在使用上面的代码后,我得到了相同的数组,该索引具有相同的数量。
我怎么能这样做 请帮助。答案 0 :(得分:2)
尝试以下解决方案:
$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);
<强>输出:强>
[{
"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"
}]