1. 程式人生 > >php獲取多維陣列中某個下標值

php獲取多維陣列中某個下標值

<?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 "<pre>"; $aa = searchMultiArray($arr1, 'id'); sort($aa); print_r($aa); echo "</pre>"; exit;

這裡寫圖片描述

/*  
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 '<pre>';    
print_r (array_get_by_key($r, 's'));  

下面這個方法,採用PHP的閉包語法。這個要在php5.3以上才可以執行

<?php  
$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;  
}