在数组中搜索值并获取数组

时间:2013-02-26 02:14:13

标签: php arrays search

我正在尝试使用数组来搜索数组内部的值,然后获取该值所在的完整数组并将其添加到数组中。下面是从中获取值的数组:

Array (
    [0] => Array ( [ID] => 138 [dimmer] => 5 [order] => 1 [double] => 0 [location1] => DSR [location2] => Stage Pockets ) 
    [1] => Array ( [ID] => 139 [dimmer] => 6 [order] => 1 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
    [2] => Array ( [ID] => 140 [dimmer] => 7 [order] => 2 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
    [3] => Array ( [ID] => 141 [dimmer] => 8 [order] => 2 [double] => 0 [location1] => DSR [location2] => Stage Pockets )
)

我正在尝试使用以下搜索功能获取dimmer的值:

function search($array, $key, $value)
{
  $results = array();

  if (is_array($array))
  {
      if (isset($array[$key]) && $array[$key] == $value)
          $results[] = $array;

      foreach ($array as $subarray)
          $results = array_merge($results, search($subarray, $key, $value));
  }

  return $results;
}

下面使用$chan值作为整数来使用上面的函数来搜索数组。然后foreach应该通过$patch数组并从上面的数组中选择数组(只返回一个空数组),尽管它不会这样做,除非你更改{{ 1}}使用$patch_single['dimmer']等字符串。

"7"

用于获取 $patch = search($patch, 'Channel', $chan); foreach ($patch as $patch_single) { print_r($patch_single); $dim_single = intval($patch_single['dimmer']); echo $dim_single; $dimmers = search($dimmers, 'dimmer', $dim_single); } 的数组位于$patch_single['dimmer']内:

foreach

感谢您的建议。

2 个答案:

答案 0 :(得分:0)

嗯,我看到你有二维数组。为什么你不使用它?

foreach($array as $row) { 
    if ($row['dimmer'] == $myValue) { $newArray[] = $row; } 
}

答案 1 :(得分:0)

试试这个:

$arr       = Array (Array ( "ID" => 138, "dimmer" => 5, "order" => 1, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ), 
                    Array ( "ID" => 139, "dimmer" => 6, "order" => 1, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ),
                    Array ( "ID" => 140, "dimmer" => 7, "order" => 2, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ),
                    Array ( "ID" => 141, "dimmer" => 8, "order" => 2, "double" => 0, "location1" => "DSR", "location2" => "Stage Pockets" ));

$arr       = array_filter($arr, function($ar) {
   return ($ar['dimmer'] == '7' );
});
echo "<pre>";
print_r($arr);

输出:

Array
(
    [2] => Array
        (
            [ID] => 140
            [dimmer] => 7
            [order] => 2
            [double] => 0
            [location1] => DSR
            [location2] => Stage Pockets
        )

)

参考:http://php.net/manual/en/function.array-filter.php