[英]PHP Search Multidimensional Array for Value
I have the following array: 我有以下数组:
Array (
[0] => Array ( [Country] => Americas [Out_Count] => 14 )
[1] => Array ( [Country] => Belgium [Out_Count] => 2 )
[2] => Array ( [Country] => China [Out_Count] => 33 )
[3] => Array ( [Country] => France [Out_Count] => 7 )
)
I have a variable as follows: 我有一个变量,如下所示:
$los = 'Belgium';
What I'd like to do is search the array and bring back the value of Out_Count
to a variable. 我想做的是搜索数组并将Out_Count
的值Out_Count
一个变量。
I can use the following: 我可以使用以下内容:
$key = array_search($los, array_column($outs, 'Country'));
This brings back the Key, in this case 1
for Belgium but I need the Out_Count
value and I'm utterly stumped on how to achieve this. 这带回的关键,在这种情况下, 1
比利时,但我需要的Out_Count
价值,我完全难倒就如何实现这一目标。
Any ideas and thoughts welcomed. 欢迎任何想法。
Nice choice of array_column()
! 不错的选择array_column()
! Just extract an array with Country
as the key and Out_Count
as the value: 只需提取一个数组,将Country
作为键,将Out_Count
作为值:
$los = 'Belgium';
$result = array_column($outs, 'Out_Count', 'Country')[$los];
To do it your way: 按照自己的方式做:
$los = 'Belgium';
$key = array_search($los, array_column($outs, 'Country'));
$result = $outs[$key]['Out_Count'];
Or: 要么:
$result = $outs[array_search($los, array_column($outs, 'Country'))]['Out_Count'];
Try this: 尝试这个:
$array = array(
array('Country' => 'Americas', 'Out_Count' => 14),
array('Country' => 'Belgium', 'Out_Count' => 2),
array('Country' => 'China', 'Out_Count' => 33),
array('Country' => 'France', 'Out_Count' => 7)
);
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;
}
Ouput: 输出继电器:
$Out_Count = search($array, 'Country', 'Belgium');
echo $Out_Count[0]['Out_Count']; //print 2
$Out_Count = search($array, 'Country', 'France');
echo $Out_Count[0]['Out_Count']; //print 7
In this way,you have the complete array that you have searched and you can access it. 这样,您便拥有了已搜索的完整阵列,您可以对其进行访问。
print_r($Out_Count);
Array
(
[0] => Array
(
[Country] => Belgium
[Out_Count] => 2
)
)
You can write your custom function like this 您可以这样编写自定义函数
function my_custom_array_search($array, $search)
{
foreach($array as $single)
{
if($single['Country']==$search)
{
return $single['Out_Count'];
}
}
return '';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.