检查数组的数组是否包含某个字符串

时间:2012-08-11 00:56:57

标签: php arrays

在将任何新子数组添加到父数组之前,我正在检查以确保数组数组不包含某些字符串

我想确保如果存在具有相同websitecondition的数组,则不会将新的子数组添加到父数组中。

例如在此示例中,$newArr不得插入数组$arr,因为它们已经存在一个具有相同website和{{{ 1}}。

condition

我正在寻找一个简单的解决方案,因为在父数组上使用函数$arr = array( array( 'website' => 'amazon', 'price' => 20, 'location' => 'uk', 'link' => '...', 'condition' => 'new' ), array( 'website' => 'abe', 'price' => 20, 'location' => 'uk', 'link' => '...', 'condition' => 'new' ) ); $newArr = array( 'website' => 'amazon', 'price' => 60, 'location' => 'uk', 'link' => '...', 'condition' => 'new' ) 是不够的。

到目前为止

代码

in_array

2 个答案:

答案 0 :(得分:1)

您每次循环$arr以查找$website$condition(始终为'new'?),或者您可以保留找到的密钥的辅助数组。如果您每次都以空$arr开头,那么第二种方法会更快。

$arr = array();
$keys = array();

foreach($table->find('tr.result') as $row){

   if(...){                  
      ...
      $condition = 'new'; // set as needed

      // track seen keys
      $key = $website . '|' . $condition; // assumes neither field contains '|'
      if (!isset($keys[$key])) {
         $keys[$key] = true;
         $arr[] = array(...);
      }
   }            
}

答案 1 :(得分:1)

我希望下面代码中的注释不言自明......我不是PHP专家,这可能不是最优雅的方式,但我相信逻辑是有道理的。显然,$ new_array对象有一些未声明的变量,但仅限于此。

我希望有所帮助,而且没有人向我投票:)

<?php
    // Original array
    $arr = array();

    foreach($result as $row) {
        // Get the new array as an object first so we can check whether to add to the loop
        $new_array = array(
            'website' => $website,
            'price' => $price,
            'location' => $location,
            'link' => $link,
            'condition' => 'new'
        );

        // If the original array is empty there's no point in looping through it
        if(!empty($arr)) {
            foreach($arr as $child) {
                // Check through each item of the original array
                foreach($new_array as $compare) {
                    // Compare each item in the new array against the original array
                    if(in_array($compare, $child)) {
                        // if there's a match, the new array will not get added
                        continue;
                    }
                }

            }   
        }

            // If there's no match, the new array gets added
        $arr[] = $new_array;
    }
?>
相关问题