首页 > 解决方案 > 从具有数组列的值给定的多维数组中搜索并获取数组值

问题描述

我有一个如下所示的数组:

$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并得到那个lngitudeand latitude value。我尝试了下面的代码,但它没有给出我的输出。

假设我在达卡搜索:

if(array_search('Dhaka', array_column($mapLocation, 'county_served')) !== False) { 
    $longitude= $mapLocation['longitude']; 
    $latitude= $mapLocation['latitude']; 
} 
echo $longitude.":".$latitude ;

输出将是628 : 389.

希望你有我的问题。

标签: php

解决方案


你真的很接近解决方案。您没有保存索引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";
}

从文档中:

返回值
如果在数组中找到 needle 的键,则返回该键,否则返回 FALSE。

这里不需要真正的foreach循环,你的想法很好。


推荐阅读