我有一个如下数组:
$mapLocation = array (
array(
'county_served'=>'Dhaka',
'longitude'=>'628',
'latitude'=>'389'),
array(
'county_served'=>'Grand Traverse1',
'longitude'=>'185',
'latitude'=>'233'),
array(
'county_served'=>'Gogebic',
'longitude'=>'73',
'latitude'=>'205'),
array(
'county_served'=>'Gratiot',
'longitude'=>'533',
'latitude'=>'540'),
array(
'county_served'=>'Hillsdale',
'longitude'=>'536',
'latitude'=>'686')
);
我想从这个数组中搜索county_served value
并得到lngitude
和latitude value
。我尝试了以下代码,但没有给出输出。
假设我被达卡搜索:
if(array_search('Dhaka', array_column($mapLocation, 'county_served')) !== False) {
$longitude= $mapLocation['longitude'];
$latitude= $mapLocation['latitude'];
}
echo $longitude.":".$latitude ;
输出将为628 : 389
。
希望你遇到我的问题。
答案 0 :(得分:0)
尝试通过简单的foreach
循环来解析位置,如以下代码所示:
$mapLocation = array(
array(
'county_served' => 'Dhaka',
'longitude' => '628',
'latitude' => '389'),
array(
'county_served' => 'Grand Traverse1',
'longitude' => '185',
'latitude' => '233'),
array(
'county_served' => 'Gogebic',
'longitude' => '73',
'latitude' => '205'),
array(
'county_served' => 'Gratiot',
'longitude' => '533',
'latitude' => '540'),
array(
'county_served' => 'Hillsdale',
'longitude' => '536',
'latitude' => '686')
);
$latitude = $longitude = '';
foreach ($mapLocation as $value) {
if ($value["county_served"] == "Dhaka") {
$latitude = $value["latitude"];
$longitude = $value["longitude"];
break;
}
}
echo "$latitude : $longitude";
答案 1 :(得分:0)
您可以尝试这样的事情:
// Create a function to search by 'county_served' so you can use it for each county_served
function getByCountyServed($array, $county_served) {
// Var if name doesn't exist
$name_exist = false;
foreach ($array as $key => $data) {
// If you find the name : echo the long et lat
if ($data['county_served'] == $county_served) {
$name_exist = true;
echo 'longitude : '. $data['longitude'] ." <br>latitude : ". $data['latitude'];
break;
}
}
// If you don't find the name : echo error message
if (!$name_exist) echo "County Served data not found";
}
getByCountyServed($mapLocation, 'Dhaka');
输出为:
longitude : 628
latitude : 389
如果您这样做:
getByCountyServed($mapLocation, 'blabla');
输出为:County Served data not found
答案 2 :(得分:0)
您真的很接近解决方案。您没有保存索引array_search()
返回:
// Save the index
$index = array_search('Dhaka', array_column($mapLocation, 'county_served'))
if($index !== false) {
// Use the index as it is a multidimensional array
$longitude= $mapLocation[$index]['longitude'];
$latitude= $mapLocation[$index]['latitude'];
echo $longitude.":".$latitude ;
} else {
echo "not found";
}
从文档中:
返回值
如果在数组中找到该针,则返回该针的键,否则返回FALSE。
这里真的不需要foreach
循环,您的想法很好。