php获取多维数组中某个下标值


function searchMultiArray(array $array, $search, $mode = 'key') {
    $res = array();
    foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
        if ($search === ${${"mode"}}) {
            if ($mode == 'key') {
                $res[] = $value;
            } else {
                $res[] = $key;
            }
        }
    }
    return $res;
}

$arr1 = Array(
    'id' => '219',
    'name' => '一汽-大众奥迪',
    'initial' => 'A',
    'list' => Array(
        0 => Array(
            'id' => '220',
            'name' => 'A3',
            'fullname' => '奥迪A3',
            'logo' => 'http://api.jisuapi.com/car/static/images/logo/300/220.jpg',
            'salestate' => '在销',
            'depth' => '3',
        ),

        1 => Array(
            'id' => '221',
            'name' => 'A4L',
            'fullname' => '奥迪A4L',
            'logo' => 'http://api.jisuapi.com/car/static/images/logo/300/221.jpg',
            'salestate' => '在销',
            'depth' => '3',
        ),
    ));

echo "
";
$aa = searchMultiArray($arr1, 'id');
sort($aa);
print_r($aa);
echo "
"
; exit;

php获取多维数组中某个下标值_第1张图片

参考文章:http://blog.csdn.net/bor10/article/details/15498669

/*  
description: 根据某一特定键(下标)取出一维或多维数组的所有值;不用循环的理由是考虑大数组的效率,把数组序列化,然后根据序列化结构的特点提取需要的字符串  
*/    
function array_get_by_key(array $array, $string){    
    if (!trim($string)) return false;    
    preg_match_all("/\"$string\";\w{1}:(?:\d+:|)(.*?);/", serialize($array), $res);    
    return $res[1];    
}    

$r = array('id'=> 1, 's'=> 23, 'a' => array('s' => 123, array(1, 2, 's' => "asdasdgsadggsadg")));    
echo '
';    
print_r (array_get_by_key($r, 's'));  

下面这个方法,采用PHP的闭包语法。这个要在php5.3以上才可以执行

  
$arr = array('id'=> 1, 's'=> 23, 'a' => array('s' => 123, array(1, 2, 's' => "asdasdgsadggsadg")));   

$result = array_filter($arr, function ($var) {     
  $found = false;  
  array_walk_recursive($var, function ($item, $key) use (&$found) {    
    $found = $found || $key == "s";  
  });  
  return $found;  
});  

var_dump($result);  

递归的方法:

function getArray($array, $index) {  
    if (!is_array($array)) return null;  
    if (isset($array[$index])) return $array[$index];  
    foreach ($array as $item) {  
        $return = getArray($item, $index);  
        if (!is_null($return)) {  
            return $return;  
        }  
    }  
    return null;  
}  

你可能感兴趣的:(php)