我正在尝试对JSON数组进行排序,并删除用户告诉要删除的页面的项目。我使用了一些回声来查看值是否匹配,即使$ value ['AD']和$ lineToRemove的值相同,我的If语句也没有捕获它,它跳到了Else部分。我试过没有我的值是字符串,我尝试过===,我尝试了一些不同的解决方案。
这是我目前的代码。
$str = file_get_contents($file2);
$json = json_decode($str, true); // decode the JSON into an associative array
$match = "We have a match!";
$test = "Sorry, no match found.";
foreach ($json as $field => &$value) {
if ((string)$value['AD'] == (string)$lineToRemove) {
echo '<pre>' . print_r($match, true) . '</pre>';
unset($json[$field]);
$json = array_values($json);
var_dump($json);
}
else {
echo '<pre>' . print_r($test, true) . '</pre>';
}
}
$finalArray = json_encode($json);
file_put_contents($file2, $finalArray);
$ lineToRemove是用户尝试删除的文件名的变量。以下是我的JSON示例:
[
{
"AD":"image-1.png",
"DURATION":1000
}
]
我已经尝试了this问题的答案,但它没有用,我现在的代码是我最接近这个工作的代码。
答案 0 :(得分:0)
我明白了。变量$ lineToRemove在它的末尾有一个换行符,从而使它不同。如果有人感兴趣,这是工作代码。
// Get contents of JSON array to remove items from the JSON array
$str = file_get_contents($file2);
$json = json_decode($str, true); // decode the JSON into an associative array
// Loop through all of the items in the JSON array to find the file you want to delete
foreach ($json as $field => &$value) {
// Remove the line break at the end of the $lineToRemove variable so you
// can compare it to the $value['AD'] variable
$lineToRemove = str_replace("\n", '', $lineToRemove);;
if ($value['AD'] == $lineToRemove) {
// Remove $lineToRemove from JSON array
unset($json[$field]);
$json = array_values($json);
}
}
// Save new array to JSON file
$finalArray = json_encode($json);
file_put_contents($file2, $finalArray);