2010-09-23 39 views
-1

得到陣列子陣我的下一個層次陣列:PHP的關鍵

Array(
[1005] => Array(
       [1000] => Array(
           [1101] => ... 
           [1111] => ... 
          ) 
       ) 
) 

在我的功能我送$標識。我的任務是通過這個Id返回一個數組。 例如:getArray(1000)應該返回下一個數組:

Array(
            [1101] => ... 
            [1111] => ... 
           ) 

我如何做呢?謝謝。

+0

Medoo? http://stackoverflow.com/questions/3776798/php-array-recursion – Wernight 2010-09-23 09:52:03

+0

這是下一個任務。 – pltvs 2010-09-23 09:54:09

+0

然後問題應該標記爲'任務'或'行使'或書面表明它不是個人問題,而​​是行爲。 – Wernight 2010-09-23 12:04:37

回答

5

這裏是一個遞歸實現的getArray

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; 
} 

這裏是一個迭代實現的getArray

function getArray($array, $index) { 
    $queue = array($array); 
    while (($item = array_shift($queue)) !== null) { 
     if (!is_array($item)) continue; 
     if (isset($item[$index])) return $item[$index]; 
     $queue = array_merge($queue, $item); 
    } 
    return null; 
} 
+0

+1打我的迭代方法 – 2010-09-23 10:07:46

3

而且回答使用了recursive iterator

function getArray($array, $index) { 
    $arrayIt = new RecursiveArrayIterator($array); 
    $it = new RecursiveIteratorIterator(
     $arrayIt, 
     RecursiveIteratorIterator::SELF_FIRST 
    ); 
    foreach ($it as $key => $value) { 
     if ($key == $index) { 
      return $value; 
     } 
    } 
    return null; 
} 

或者,如果你真的想要得到幻想,那麼你就是d使用filter iterator

class IndexFilterIterator extends FilterIterator { 
    protected $index = ''; 
    public function __construct($iterator, $index) { 
     $this->index = $index; 
     parent::__construct($iterator); 
    } 
    public function accept() { 
     return parent::key() == $index; 
    } 
} 

function getArray($array, $index) { 
    $arrayIt = new RecursiveArrayIterator($array); 
    $it = new RecursiveIteratorIterator(
     $arrayIt, 
     RecursiveIteratorIterator::SELF_FIRST 
    ); 
    $filterIt = new IndexFilterIterator($it, $index); 
    $filterIt->rewind(); 
    if ($filterIt->valid()) { 
     return $filterIt->current(); 
    } 
    return null; 
} 
+0

感謝它爲我工作:) – 2013-08-18 16:43:02