首页 > 解决方案 > 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
        }
    }

标签: phparraysjsonforeach

解决方案


$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;
        }
    }
}

推荐阅读