PHP中的JSON更新:重复



当我试图更新数据库中的json时,遇到了一个奇怪的问题。这是我的代码:

// Update content of user cart                    
$contentJSON = json_decode($userCart['content'],true);
$newJSONContent;
$wineNotExist = true;
$index = 1;
foreach($contentJSON as $key) {
// Update content if wine is already in user cart
if ($key['wineId'] === $wineId) {

$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $key['wineQuantity'] + $wineQuantity;
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
$wineNotExist = false;
} else {
$contentObject->wineId = $key['wineId'];
$contentObject->wineQuantity = $key['wineQuantity'];
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
}
$index++;
}
if ($wineNotExist) {
$dataKey = strval($index);
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $wineQuantity;
$newJSONContent->$dataKey = $contentObject;
}

因此,我决定构建一个新的JSON并解析前者;此外,如果json不包含wineId,我们在json中创建了一个新的数据输入,但这一部分用正确的键替换了以前的键,并创建了正确的键,正如您在AJAX响应中看到的那样:

当它是相同的葡萄酒时的响应ID

{
"code": 200,
"status": "success",
"message": "This wine has been added to your cart",
"content": {
"1": {
"wineId": 2,
"wineQuantity": 3
}
},
"index": true
}

当wineId未包含在购物车中时的响应

{
"code": 200,
"status": "success",
"message": "This wine has been added to your cart",
"content": {
"1": {
"wineId": 5,
"wineQuantity": 1
},
"2": {
"wineId": 5,
"wineQuantity": 1
}
},
"index": true
}

我不明白为什么if中的指令替换了以前的值,你知道为什么吗?

当我在if指令中为contentObject使用另一个变量名时,代码有效,但为什么?因为$contentObject是foreach循环中的局部变量

对不起我的英语,我是法国人。

它与此代码一起工作,所以问题是$contentObject具有以前的值,而它是本地变量,它是PHP特有的吗?

// Update content of user cart                    
$contentJSON = json_decode($userCart['content'],true);
$newJSONContent;
$wineNotExist = true;
$index = 1;
foreach($contentJSON as $key) {
// Update content if wine is already in user cart
if ($key['wineId'] === $wineId) {
$contentObject=null;
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $key['wineQuantity'] + $wineQuantity;
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
$wineNotExist = false;
} else {
$contentObject=null;
$contentObject->wineId = $key['wineId'];
$contentObject->wineQuantity = $key['wineQuantity'];
$dataIndex = strval($index);
$newJSONContent->$dataIndex = $contentObject;
}
$index++;
}

if ($wineNotExist) {
$contentObject=null;
$dataKey = strval($index);
$contentObject->wineId = $wineId;
$contentObject->wineQuantity = $wineQuantity;
$newJSONContent->$dataKey = $contentObject;
}

最新更新