我有一个嵌套数组,我想知道是否有一种方法可以使它滑动,所以将嵌套数组作为单独的数组
Array
(
[0] => Array
(
[menu] => Array
(
[pizza] => Array
(
[Tomato & Cheese] => Array
(
[small] => 5.50
[large] => 9.75
)
[Olives] => Array
(
[small] => 6.85
[large] => 10.85
)
)
[Speciality Pizzas] => Array
(
[Our Special] => Array
(
[ingredients] => Array
(
[0] => Tomatoes
[1] => Olives
[2] => Spinach
[3] => Fresh Garlic
[4] => Mozzarella & Feta Cheese
) --- theres more but you get the idea
现在我想要一个包含所有比萨饼的新阵列,但不知道名字“披萨”
目前我可以这样做:
$array = array(json_decode($json, true));
$pizzas = (array)$array[0]['menu']['pizza']
但是如果菜单改变内容(但不是结构)并且如果'披萨'变成'沙拉',则上述将失败。是一种创建上面没有名称
的比萨饼阵列的方法由于
答案 0 :(得分:1)
$array = array(json_decode($json, true));
$menu = (array)$array[0]['menu'];
foreach($menu as $item => $item_Data){
//$item might be pizza for example
//$item_Data might be Olives or Our special. Now you have to consider what to do with this. Maybe next foreach loop ?
}
答案 1 :(得分:0)
现在你的数组有相关数据的并行部分。如果你做了类似的事情怎么样:
$food_choices = array(
'pizza' => array(
'Tomato & Cheese' => array(
'type' => 'regular',
'prices' => array(...),
'ingredients' => array(...)
),
'Our Special' => array(
'type' => 'specialty',
'prices' => array(...),
'ingredients' => array(...)
),
),
'salads' => array(
'Caesar' => array(...);
'Tossed' => array(...);
)
)
其中所有与任何一个菜单项相关的信息都在meu树的同一分支中。然后访问任何一个披萨的信息就像:
$data = $food_choices['pizza']['Tomato & Cheese'];
echo 'The large of this pizza costs $', $data['prices']['large'];
echo 'The small Caesar salad contains ', implode($food_choices['salad']['Caesar']['ingredients);
答案 2 :(得分:0)
一系列foreach循环可能会这样做,即使我不知道你在做什么。
<?php
$pizza = '';
foreach ($array as $food) {
$pizza .= $food;
if (is_array($food)) {
foreach ($food as $option) {
$pizza .= " > " . $option;
if (is_array($option)) {
foreach ($option as $value) {
//etc
}
}
}
}
}
?>
答案 3 :(得分:0)
要了解数组中的键,请使用array_keys
函数(Demo):
$array = array(array('menu' => array(/* ... */))); # your array
print_r(array_keys($array[0])); # Array(menu)