我有下面的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文件,它不會將「活動」切換爲「不活動」。 –
檢查答案。 –