【发布时间】:2018-10-30 03:25:13
【问题描述】:
在开始之前,我正在学习,我不会声称自己是 PHP 专家。我尝试了几种不同的方法,但这种方法让我最接近我正在寻找的东西。
我有一个要搜索的 JSON 数组,如果部分文本与数组中一行(警报)的任何部分匹配,则从数组中删除整个键。 (如果可能的话,我只希望它匹配最新的键,而不是删除所有匹配的键)
下面的代码正在处理数组中的最新项目,但无法搜索较旧的记录。
例如,
[8] => Array
(
[Code] => 9
[Alerts] => bob went away
)
[9] => Array
(
[Code] => 9
[Alerts] => randy jumped in the air
)
)
如果我调用脚本,使用“bob”这个词,它什么也找不到。如果我使用术语“randy”调用脚本,它将完美地删除键 9。然后我可以搜索术语“bob”,它将删除键 8。
这是我目前所拥有的。 (同样可能有更好的方法)
<?php
$jsondata = file_get_contents('myfile.json');
$json = json_decode($jsondata, true);
$done = 'term';
$pattern = preg_quote($done, '/');
$pattern = "/^.*$pattern.*\$/m";
$arr_index = array();
foreach ($json as $key => $value)
$contents = $value['Alerts'];
{
if(preg_match($pattern, $contents, $matches))
{
$trial = implode($matches);
}
if ($contents == $trial)
{
$arr_index[] = $key;
}
}
foreach ($arr_index as $i)
{
unset($json[$i]);
}
$json = array_values($json);
file_put_contents('myfile-test.json', json_encode($json));
echo $trial; //What did our search come up with?
die;
}
再次感谢!
【问题讨论】: