我有一个数组里面有数组。我需要找到一个与f.x有关的元素。“it”=> 9,然后从它获得国家/货币。我怎么能找到这样的元素呢?到目前为止,我做循环和检查我的ID每个数组,我相信这是可能的更容易。谢谢!
$countries = array(
array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
array('ID' => '9','Country' => 'France','Currency' => 'EUR'),
...
);更新我希望能够通过任何键搜索: ID,国家,货币
发布于 2014-01-13 14:32:17
如果数组的id是唯一的,则可以使用array_filter(),例如:
$countries = array(
array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
array('ID' => '9','Country' => 'France','Currency' => 'EUR')
);
$id = 9;
$result = array_shift(array_filter($countries, function($item) use ($id)
{
return $item['ID']==$id;
}))['Country'];-but如果id是非唯一的,上面的代码将返回国家的第一个发现id.还请注意,这种去引用方式只允许在PHP>=5.4中使用(在早期版本中,您必须先找到数组元素,然后访问它的Country键)。
若要按可使用的任何键进行搜索,请执行以下操作:
$key = 'ID';
$value = 9;
$result = array_shift(array_filter($countries, function($item) use ($key, $value)
{
//change == to === for strict comparison:
return array_key_exists($key, $item) && $item[$key]==$value;
})); //whole element, not only 'Country' key what cause if search will be by Country?发布于 2014-01-13 14:29:10
最简单的方法是修复它,因此在构建数组时,将ID作为数组的键。所以看起来就像
$countries = array(
8=>array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
9=>array('ID' => '9','Country' => 'France','Currency' => 'EUR'),
...
);然后你可以简单地做$countries[8]等等。
发布于 2014-01-13 14:32:50
类似于PHP多维数组值搜索
或
您可以将ID作为父数组的索引,并使用ID直接访问其值。例如:
$countries = array(
8 => array('ID' => '8','Country' => 'Finland','Currency' => 'EUR'),
9 => array('ID' => '9','Country' => 'France','Currency' => 'EUR'),
...
);https://stackoverflow.com/questions/21093655
复制相似问题