在 php 中访问不均匀的高级别关联数组


Access uneven high leveled associative array in php

我嵌套了超过 4 个级别的关联数组。有些值进入所有 4 个级别,而有些值在第一级结束。现在我如何从 php 访问所有值。

对于 2 级数组,我只能:

foreach($options as $o){
    foreach($m as $check){
        if(isset($check[$o])) echo $check[$o];
    }
}

以检查是否设置了值,然后使用它。但是,对于具有未知深度的数组或水平不均匀的很多级别,我该如何执行此操作。

这取决于您对"访问"的含义。如果你只想打印出值,你可以使用这样的递归函数:

function crawlArray($myArray, $depth=0) {
  foreach ($myArray as $k => $v) {
    if (is_array($v)) {
      crawlArray($v, ++$depth);
    } else {
      echo $v;
    }
  }
}
crawlArray($options);

您可以使用递归函数,如下所示:

<?php
    function getSetValues($array, $searchKeys) {
        $values = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $values = array_merge($values, getSetValues($value, $searchKeys));
            } else if (in_array($key, $searchKeys)) {
                $values[] = $value;
            }
        }
        return $values;
    }
    $values = getSetValues(array(
        'foo' => array(
            'bar' => 123,
            'rab' => array(
                'oof' => 'abc'
            ),
            'oof' => 'cba'
        ),
        'oof' => 912
    ), array('bar', 'oof')); //Search for keys called 'bar' or 'oof'
    print_r($values);
?>

这将输出:

Array
(
    [0] => 123 (because the key is 'bar')
    [1] => abc (because the key is 'oof')
    [2] => cba (because the key is 'oof')
    [3] => 912 (because the key is 'oof')
)

演示