代码之家  ›  专栏  ›  技术社区  ›  Alex Pliutau

php按键从数组中获取子数组

  •  -1
  • Alex Pliutau  · 技术社区  · 14 年前

    我有下一个层次结构数组:

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

    在我的函数中,我发送$id.和我的任务,用这个id返回一个数组。 例如: getArray(1000) 应返回下一个数组:

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

    我怎么做这个?谢谢。

    2 回复  |  直到 14 年前
        1
  •  5
  •   Gumbo    14 年前

    下面是的递归实现 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;
    }
    

    这里是一个迭代实现 获取数组 :

    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;
    }
    
        2
  •  3
  •   ircmaxell    14 年前

    以及一个使用 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;
    }
    

    或者,如果你真的想得到幻想,你可以使用 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;
    }