如何在不知道键的情况下读取嵌套数组值?
问题描述:
我是数组新手.我希望打印出所有可能的 [type] [label] [value]
的值.我希望喜欢如果有一个带有select的类型,然后显示所有带有值的标签"
I'm new in array. I wish to print out the values of all possible [type] [label] [value]
. I wish to do like "if there's a type with select, then display all labels with values"
下面是我的数组.
Array
(
[product_id] => 8928
[title] => Example of a Product
[groups] => Array
(
[8929] => Array
(
[8932] => Array
(
[type] => select
[label] => Section
[id] => pewc_group_8929_8932
[group_id] => 8929
[field_id] => 8932
[value] => Section 200
[flat_rate] => Array
(
)
)
)
)
[price_with_extras] => 0
[products] => Array
(
[field_id] => pewc_group_8929_9028
[child_products] => Array
(
[8945] => Array
(
[child_product_id] => Array
(
[0] => 8945
)
[field_id] => pewc_group_8929_9028
[quantities] => one-only
[allow_none] => 0
)
)
[pewc_parent_product] => 8928
[parent_field_id] => pewc_5d678156d81c6
)
)
该网站说看起来您的帖子大部分是代码;请添加更多详细信息."因此,这就是我所谓的lorem ipsum:D
The site is saying " It looks like your post is mostly code; please add some more details." So here's my so-called lorem ipsum :D
答
您可以使用 array_walk_recursive 相同,
array_walk_recursive($arr, function ($value, $key) {
// check if key matches with type, label or value
if (count(array_intersect([$key], ['type', 'label', 'value'])) > 0) {
echo "[$value] ";
}
});
输出
[select] [Section] [Section 200]
编辑
您可以将条件修改为
if($ key ==='type'&& $ value =='select')
编辑1
array_walk_recursive($arr, function ($value, $key) {
if($key === 'type' && $value == 'select'){
echo "[$value] ";
}
});
编辑2
function search_by_key_value($arr, $key, $value)
{
$result = [];
if (is_array($arr)) {
if (isset($arr[$key]) && $arr[$key] == $value) {
$result[] = $arr;
}
foreach ($arr as $value1) {
$result = array_merge($result, search_by_key_value($value1, $key, $value));
}
}
return $result;
}
// find array by key = type and value = select
$temp = search_by_key_value($arr, 'type', 'select');
$temp = array_shift($temp);
print_r($temp);
echo $temp['label'];
echo $temp['value'];