gpt4 book ai didi

php - 使用foreach循环获取数组的值

转载 作者:行者123 更新时间:2023-12-02 11:08:09 28 4
gpt4 key购买 nike

我有一个从android收到的数组,必须将其插入到带有字段user、product、remark、color、size、count的mysql表中。我无法获取包含大小和计数的内循环数据的值。它显示错误

$dat='[{"user":10,
"product":58,
"remarks":"ok",
"details":[{
"color":"Red",
"data":[{
"size":12,
"count":1
},
{
"size":14,
"count":2
}]
}]
},
{"user":10,
"product":60,
"remarks":"okk",
"details":[{
"color":"Black",
"data":[{
"size":10,
"count":5
},

]},{
"color":"Red",
"data":[{
"size":10,
"count":3
},

]}
]}
]';

这是我尝试过的代码。

$s = json_decode($dat, true);
print_r($s);


foreach($s as $item)
{
foreach($item as $details) {
foreach($details as $data) {

echo "user".$item['user'];
echo "product".$item['product'];
echo "remarks".$item['remarks'];
echo "color".$details['color'];
echo "size".$data['size'];
echo "count".$data['count'];


}
}
}

这是print_r($s)的输出

Array(
[0] => Array (
[user] => 10
[product] => 58
[remarks] => ok
[details] => Array (
[0] => Array(
[color] => Red
[data] => Array (
[0] => Array (
[size] => 12
[count] => 1
)
[1] => Array (
[size] => 14
[count] => 2
)
)
)
)
)
[1] => Array (
[user] => 10
[product] => 60
[remarks] => okk
[details] => Array (
[0] => Array (
[color] => Black
[data] => Array(
[0] => Array (
[size] => 10
[count] => 5
)
)
)
[1] => Array(
[color] => Red
[data] => Array (
[0] => Array(
[size] => 10
[count] => 3
)
)
)
)
)
) ;

请帮助我。提前致谢

最佳答案

foreach($s as $item)
{
echo "user".$item['user'];
echo "product".$item['product'];
echo "remarks".$item['remarks'];
foreach($item['details'] as $detail)
{
echo "color".$detail['color'];
foreach($detail['data'] as $data)
{
echo "size".$data['size'];
echo "count".$data['count'];
}
}
}

你的 json 得到 2 个逗号,你必须删除它们

"details":[{
"color":"Black",
"data":[{
"size":10,
"count":5
} <---

]},{
"color":"Red",
"data":[{
"size":10,
"count":3
} <---

]}

关于php - 使用foreach循环获取数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116906/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com