我有下面的PHP代码,它从另一个页面(通过POST发送)接收一些变量。PHP - 更改JSON文件中的值
基于Ad_id和Name ...我试图切换'激活'或'非激活'之间的状态。
但是,当我执行此(使用正确的POST数据)...它似乎并没有更新任何东西。我究竟做错了什么?
例如当我通过有效的广告发送时,名称为& status ...然后去检查JSON文件,它不会将“有效”切换为“无效”。
PHP:
<?php
// Get the post variables
$ad_id = $_GET['ad'];
$name = $_GET['name'];
$status = $_GET['status'];
// Get the JSON file
$json = file_get_contents('test.json');
// Decode Json into an array
$json = json_decode($json,true);
// Within the array.. find the ad that matches the POST variable.
foreach ($json['ads'] as $ad) {
if ($ad['id'] == $ad_id) {
// Within that Ad... find the candidate that matches the POST variable.
foreach ($ad['candidates'] as $candidate) {
if ($candidate['name'] == $name) {
// Within that candidate... check the value of 'status'.
if ($candidate['status'] == 'active') {
// If active, update the status to 'inactive'.
$candidate['status'] = 'inactive';
} else {
// If inactive, update the status to 'active'.
$candidate['status'] = 'active';
}
}
}
}
}
// Encode the array as JSON again
$json = json_encode($json);
// Save the JSON back to the server
file_put_contents('test.json', $json, LOCK_EX);
?>
JSON:
{
"ads": [
{
"id": "12345678",
"hirername": "Demo Bar",
"candidates": [
{
"status": "active",
"name": "Gregory Jones",
"dist": "Richmond (4km away)",
"exp1": "Barman at City Bar for 2 years",
"avail1": "Mon to Fri - Morning, Evening & Night",
"visa": "Australian Citizen",
"call": "0413451222"
},
{
"status": "active",
"name": "Jackie Linton",
"dist": "Box Hill (13km away)",
"exp1": "Bar girl at Collins Bar for 1 year",
"avail1": "Mon to Fri - Morning & Evening",
"visa": "Working holiday visa",
"call": "0413456555"
}
]
}
]
}
哪部分不工作? –
当我通过有效的广告,名称和状态发送...然后去检查JSON文件,它不会将“活动”切换为“不活动”。 –
检查答案。 –