php - json对象上的嵌套foreach循环未返回正确的值和结构
问题描述
我不知道为什么我的数组循环不起作用。
我正在尝试循环解码的 JSON 对象
+"categoryCode": "1122"
+"category_description": "This is the category Description"
+"products": array:24 [▼
0 => {#999 ▼
+"pricing": {#1011 ▼
+"MainPrice": "40.00"
}
+"productInfo": {#1009 ▼
+"product": {#1014 ▼
+"product_type": {#1015 ▼
+"desc": "Test Product"
+"quantDetails": 3.0
}
}
}
}
并建立一个新的$priceResult
并根据我需要的值我想要数组第一级的类别信息,然后是产品信息。
为什么这个循环不能正确构建我的新数组?当我转储 $priceResult 时,我得到了类别信息,但随后我只得到了同一级别的价格和一堆空值。我是否错误地循环和构建新数组?
$priceResult = array();
foreach($pricing->categories as $category){
$priceResult[] = $category->categoryCode;
$priceResult[] = $category->category_description;
foreach($category->products as $product){
foreach ($product->pricing as $price => $amount) {
$priceResult[] = $amount;
}
foreach($product->productInfo as $info){
foreach($info->product as $product){
foreach($product->product_type as $type){
$priceResult[] = $type->desc;
$priceResult[] = $type->quantDetails;
}
}
}
}
}
更新输出:
这是一些错误输出的示例
0 => "CategoryOne"
1 => "1122"
2 => "This is the category Description"
3 => null
4 => null
5 => null
6 => null
7 => null
8 => null
9 => null
10 => null
11 => null
12 => null
13 => null
14 => null
15 => null
16 => null
17 => null
18 => null
19 => "40.00"
20 => null
21 => null
22 => null
23 => null
24 => null
25 => null
26 => null
27 => null
28 => null
29 => null
30 => null
31 => null
32 => null
33 => null
34 => null
35 => null
36 => "50.00"
更新所需的输出:
CategoryName : TestCategory
CategoryDescription: For Testing
Products{
0{
Product_code : 123,
CountNumber : 12,
ProductDescription: Test Product,
price_amount : 150.00
},
1{
Product_code : 112,
CountNumber : 32,
ProductDescription: Test Product 2,
price_amount : 250.00
}
}
解决方案
$product->pricing
并且$product->productInfo
是单个对象,而不是对象数组。如果要遍历对象的属性,可以使用get_object_vars()
返回关联数组。
foreach($pricing->categories as $category){
$priceResult[] = $category->categoryCode;
$priceResult[] = $category->category_description;
foreach($category->products as $product){
foreach (get_object_vars($product->pricing) as $amount) {
$priceResult[] = $amount;
}
foreach (get_object_vars($product->productInfo) as $info) {
$priceResult[] = $info->desc;
$priceResult[] = $info->quantDetails;
}
}
}
推荐阅读
- c# - 使用计时器使用 C# VSTO 检查 Outlook 连接状态
- python - 无法在 django-mapbox-location-field Django 中显示数据
- php - PHP如何:多个提交按钮持有不同的数据但相同的值
- c - 为什么解决三对角系统的并行循环归约在 openMP 中不能很好地扩展?
- python - GEKKO 中的中间结构中的无效元素错误
- javascript - CSV 文件控制台日志记录未定义 - JS
- node.js - 您可以在 express 的 findbyid 路由内调用所有帖子的函数吗
- c# - 如何在 C# 中实现 dapper 使用的类
- r - 如何将函数应用于 R 中 SparkR 中的特定行,同时保持早期结果不变
- python - stats.ttest_ind() 与学生独立 t 检验的“手动”计算:不同的结果