[英]Returning values from a multidimensional array php
I'm hoping there is a better way of returning the values from each of cy_GB['value]
and en_GB['value]
from the array below: 我希望有更好的方法从下面的数组中返回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] =>
)
This is what I've tried. 这就是我尝试过的。 I should also use more meaningful names.: 我还应该使用更有意义的名称:
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'];
}
}
}
}
I know this kind of thing has been asked many times before so I apologise for that. 我知道这种事情已经被问过很多次了,对此我深表歉意。 any help would be most appreciated. 非常感激任何的帮助。
Something like this could work: 这样的事情可能会起作用:
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');
It's not shorter, but in my opinion more elegant, and it should work with any object/array structure. 它并不短,但我认为它更优雅,并且可以与任何对象/数组结构一起使用。
Untested. 未经测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.