我有一个带键值的多维数组。我想循环数组中的数据,但我不知道如何。
这是我的阵列:
{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}
如何循环/ foreach该数组?
我想foreach中有一个foreach,但我不知道该怎么做。
答案 0 :(得分:0)
在array_walk_recursive的手册中,有一个可能适合你的例子 http://php.net/manual/en/function.array-walk-recursive.php
$arr = json_decode($str, true); //$str is your json string
array_walk_recursive($arr, 'test_print');
function test_print($item, $key)
{
echo "[$key]: $item\n";
}
如果您只想输出数组的某些元素,可以创建一个包含要输出的项目的数组,并将其传递给函数。
然后使用in_array来查看它是否是输出。
答案 1 :(得分:-1)
使用此代码:
<?php
$jsonData = '{
"success": "1",
"order_details": [
{
"item_order": 5,
"address": "155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India",
"contact": "95303709",
"total_price": "3330.0",
"order_place": "18-05-25 06-07-20",
"preparing_date_time": "",
"preparing_status": "Deactivate",
"dispatched_date_time": "",
"dispatched_status": "Deactivate",
"delivered_date_time": "",
"delivered_status": "Deactivate",
"menu": [
{
"menu_name": "demo item",
"item_amt": "200",
"Ingredients": [
{
"ingredients_name": "burger",
"ingredients_price": "200"
},
{
"ingredients_name": "pizza1",
"ingredients_price": "800"
}
]
}
]
}
]
}';
$jsonDecode = json_decode($jsonData);
foreach ($jsonDecode->order_details as $orderDetail) {
echo "Item order: " . $orderDetail->item_order;
echo "<br>";
echo "Address: " . $orderDetail->address;
echo "<br>";
echo "Contact: " . $orderDetail->contact;
echo "<br>";
foreach ($orderDetail->menu as $menuItem) {
echo "Menu Name: " . $menuItem->menu_name;
echo "<br>";
echo "Item amt: " . $menuItem->item_amt;
echo "<br>";
foreach ($menuItem->Ingredients as $ingredientsItem) {
echo "Ingredients name: " . $ingredientsItem->ingredients_name;
echo "<br>";
echo "Ingredients price: " . $ingredientsItem->ingredients_price;
echo "<br>";
}
}
}
输出:
Item order: 5
Address: 155, Mani Nagar Society, Nana Varachha, Surat, Gujarat 395006, India
Contact: 95303709
Menu Name: demo item
Item amt: 200
Ingredient name: burger
Ingredient price: 200
Ingredient name: pizza1
Ingredient price: 800