如何在搜索字符串的基础上删除数组索引

时间:2017-05-01 08:49:38

标签: php arrays

说我有一个类似

的数组
    Array 
(
  [0] => Array ( [name] => test1 [type] => this1 [location] => 1 ) 
  [1] => Array ( [name] => test2 [type] => this2 [location] => 2 )
  [2] => Array ( [name] => testing2 [type] => this3 [location] => 3 )
)

并且我想删除密钥,它包含数组的任何位置" testing"只要它有这个词,就不必是完全匹配。

理想情况下[2]应该删除/取消设置,因为它包含该单词。我怎样才能做到这一点。

预期输出:

    Array 
(
  [0] => Array ( [name] => test1 [type] => this1 [location] => 1 ) 
  [1] => Array ( [name] => test2 [type] => this2 [location] => 2 )
)

谢谢

3 个答案:

答案 0 :(得分:2)

希望这会帮到你..我们正在使用implodestristr,我们正在使用implode将数组加入字符串并使用stristr <搜索字符串< / p>

Try this code snippet here     

ini_set('display_errors', 1);

$rows=Array ( 
    0 => Array ( "name" => "test1","type" => "this1", "location" => 1 ),
    1 => Array ( "name" => "test2" ,"type" => "this2", "location" => 2 ),
    2 =>Array ( "name" => "testing2","type" => "this3", "location" => 3 ));
$wordToSearch="testing";
foreach($rows as $key => $value)
{
    if(stristr(implode("", $value), $wordToSearch))
    {
        unset($rows[$key]);
    }
}
print_r($rows);

答案 1 :(得分:0)

你可以使用

unset(array[2]);

谢谢

答案 2 :(得分:0)

此代码适用于您

 $search = "testing";
 $b =array(array ( 'name' => "test1", 'type' => "this1", 'location' => 1 ) ,
        array ( 'name' => "test2" ,'type' => "this2", 'location' => 2 ) ,
     array ( 'name' => "testing2", 'type'=> "this3", 'location' => 3 ));
foreach ($b as $key=>$val)    {    
   foreach($val as $key1=>$val1){
      if (strpos($val1,$search) !== FALSE) { 
         unset($b[$key]);
         break;
      }
   }
}
echo '<pre>';print_r($b);