从多维数组php返回值

时间:2015-03-24 10:00:35

标签: php arrays multidimensional-array

我希望有更好的方法可以从下面的数组中返回cy_GB['value]en_GB['value]中每个值的值:

MultilingualSelectAttributeTypeOptionList Object (
    [options:MultilingualSelectAttributeTypeOptionList:private] => Array
        (
            [0] => MultilingualSelectAttributeTypeOption Object
                (
                    [error] => 
                    [id] => 7
                    [values] => Array
                        (
                            [cy_GB] => Array
                                (
                                    [id] => 13
                                    [value] => Audio described
                                )

                            [en_GB] => Array
                                (
                                    [id] => 14
                                    [value] => Audio described
                                )

                        )

                    [th] => TextHelper Object
                        (
                        )

                )

            [1] => MultilingualSelectAttributeTypeOption Object
                (
                    [error] => 
                    [id] => 3
                    [values] => Array
                        (
                            [cy_GB] => Array
                                (
                                    [id] => 5
                                    [value] => BSL signed
                                )

                            [en_GB] => Array
                                (
                                    [id] => 6
                                    [value] => BSL signed
                                )

                        )

                    [th] => TextHelper Object
                        (
                        )

                )

        )

    [error] => 
)

这是我尝试过的。我还应该使用更有意义的名字。:

foreach ($selectedOptions as $row) {

    foreach ($row as $key) {

        foreach ($key as $k => $v) {

            if($k == 'cy_GB') {
                echo $v['value'];
            }

            if($k == 'en_GB') {
                echo $v['value'];
            }

        }

    }

}

我知道此事已被多次询问过,所以我为此道歉。任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:2)

这样的事情可行:

function findKeyRec($obj, $search) {

  if( !is_array( $obj ) && !$obj instanceof Traversable ) return;

  foreach($obj as $key => $value) {
    if($key == $search) {
        echo $value['value'];
    } else {
       findKeyRec($value, $search);
    }
  }
}

findKeyRec($ar, 'cy_GB');
findKeyRec($ar, 'en_GB');

它不短,但在我看来更优雅,它应该适用于任何对象/数组结构。

未测试。