代码之家  ›  专栏  ›  技术社区  ›  user3669555

多维数组搜索部分单词或短语并移除键

  •  2
  • user3669555  · 技术社区  · 6 年前

    在我开始之前,我正在学习,我不会自称是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;
    }
    

    再次感谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Barmar    6 年前

    问题是使用 $contents 不在房间里 foreach 环循环体中只有一条语句:

    $contents = $value['Alerts'];
    

    循环结束时, $contents 包含最后一个警报值,然后在它之后的代码块中使用。

    你需要把这句话放在括号里。

    <?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;
    }
    

    您应该使用编辑器的功能自动缩进代码,这会使类似的问题更加明显。

        2
  •  0
  •   user3669555    6 年前

    如果有人需要的话,我可以使用下面的方法让它工作。这比我最初打算的要简单一点。这将在找到文本的第一个键处停止。要删除所有记录,只需删除“break”,它将删除包含所述文本或短语的所有键。

    $pattern = preg_quote($done, '/');
    $pattern = "/^.*$pattern.*\$/m";
    $arr_index = array();
    foreach ($json as $key => $contents) 
    {
        if(preg_match($pattern, $contents['Alerts'], $matches)) {
          unset($json[$key]);
          break; 
       }
    }
    $json = array_values($json);
    
    file_put_contents('myfile-test.json', json_encode($json));