如何在php中以简单的方式过滤多数组中的元素

时间:2013-12-12 09:43:15

标签: php arrays multidimensional-array

我有多个阵列的位置,我想过滤一个匹配的位置(country_name,city_name) 如果匹配两个数组或许多......那么只给我一个数组

$country = 'United States';
$city = 'Miami';

$locations = 
    Array ( 
    "count" => 6,
    "query" => "Miami",
    "locations" => Array ( 
    "0" => Array ( 
    "id" => 4621 ,
    "name" => "Miami, FL, United States - 661 hotels" ,
    "country_name" => "United States ",
    "country_code" => "US" ,
    "state_code" => "FL" 
    ),
    "1" => Array (
    "id" => 4633 ,
    "name" => "Miami, OK, United States - 86 hotels" ,
    "country_name" =>" United States",
    "country_code" => "US" ,
    "state_code" => "OK" 
        ),
    "2" => Array (
    "id" => 21670 ,
    "name" =>" South Miami, FL, United States - 30 hotels",
    "country_name" => "United States" ,
    "country_code" => "US" ,
    "state_code" => "FL"
        ) 
    )
    );

3 个答案:

答案 0 :(得分:0)

$newArray= array();
foreach ($locations['locations'] as $key => $value) {
    if (strpos($value['name'],$city) !== false) {
       if(strpos($value['country_name'],$country) !== false){
            $newArray = $value; 
           break;
       }
    }
}
print_r($newArray);

这样我就会返回一个新数组,其中包含具有您搜索的值的数组。这是你想要的吗?

编辑:看看它是否是您想要的结果。

答案 1 :(得分:0)

$locationArray = $locations['locations'];
foreach($locationArray as $location) {
    if ((strpos($location['country_name'], $country) !== false) && (strpos($location['name'], $country) !== false)) {
        return $location;
    }
}

答案 2 :(得分:0)

定义一个函数,验证项是否符合您的条件。您可以在array_filter()或循环中使用该函数。

$locations = array( 
  "count" => 6,
  "query" => "Miami",
  "locations" => array( 
    "0" => array( 
      "id" => 4621 ,
      "name" => "Miami, FL, United States - 661 hotels" ,
      "country_name" => "United States ",
      "country_code" => "US" ,
      "state_code" => "FL" 
    ),
    // ...
  )
);

// define the filter function
$country = 'United States';
$city = 'Miami';
$validate = function($item) use ($country, $city) {
  return (
    trim($item['country_name']) == $country &&
    0 === strpos($item['name'], $city.',')
  );
};

// filter
var_dump(
  array_filter($locations['locations'], $validate)
);

// find first
$location = NULL;
foreach ($locations['locations'] as $location) {
  if ($validate($location)) {
    $result = $location;
    break;
  }
}
var_dump($result);