在数组中查找常用值

时间:2013-01-28 10:07:05

标签: php arrays

您好我有两个数组

$arrays = Array ( [0] => 2 [1] => 3 ) ;

$result_array = Array ( 
  [0] => Array ([0] => 1 
                [1] => sa 
                [2] => asa 
                [3] => sas 
                [4] => asa
                [5] => ada
                [6] => Y ) 
  [1] => Array ([0] => 2 
                [1] => TEST1
                [2] => TEST1
                [3] => TEST1
                [4] => TEST1 
                [5] => Coverage
                [6] => Y ) 
  [2] => Array ([0] => 3 
                [1] => TEST2
                [2] => TEST2
                [3] => TEST2
                [4] => TEST2
                [5] => Coverage
                [6] => Y ) );

我想要实现的是从$ result_array获取所有数组,其中应该包含$ arrays的值

我试过了$new_array = array_intersect($arrays,$result_array);

foreach($result_array as $array)
  {
for($i=0;$i<count($arrays);$i++)
{
    echo $arrays[$i];
    $key = array_search($array, $arrays[$i]); 
    $result = $array[$key];
}

break;
  }

第二个给我这个错误Warning: array_search() [function.array-search]: Wrong datatype for second argument in D:\xampp\htdocs\WEB_1\index.php on line 96

实现这一目标的其他任何方式?

3 个答案:

答案 0 :(得分:1)

简单如π

$arrays = array(2,3);
$result_array = array( 
  0 => array(0 => "1", 
                1 => "sa",
                2 => "asa", 
                3 => "sas", 
                4 => "asa",
                5 => "ada",
                6 => "Y" ), 
  1 => array(0 => "2", 
                1 => "TEST1",
                2 => "TEST1",
                3 => "TEST1",
                4 => "TEST1", 
                5 => "Coverage",
                6 => "Y" ), 
  2 => array(0 => "3", 
                1 => "TEST2",
                2 => "TEST2",
                3 => "TEST2",
                4 => "TEST2",
                5 => "Coverage",
                6 => "Y" ));
$common = array();

foreach ($result_array as $arr) {
  foreach($arrays as $search){
    if(in_array($search, $arr)){
      $common[] = $arr;
    }
  }

}

print_r($common);

答案 1 :(得分:0)

像这样使用....交换array_search()函数中的参数。

$result = array();
foreach($result_array as $array)
{
    for($i=0; $i<count($arrays); $i++)
   {
       echo $arrays[$i];
       $key = array_search($arrays[$i], $array); 
       $result[] = $array[$key];
   } 
}

答案 2 :(得分:0)

尝试以下代码

$new_array=array();
            foreach($arrays as $key=>$val)
            {
                if(array_key_exists($val,$result_array))
                {
                    $new_array=$result_array[$val];
                }
            }