在PHP中解析stdClass对象的字符串

时间:2019-01-06 16:22:13

标签: php string parsing stdclass

我有一个由stdClass对象组成的字符串数组,但我无法正确解析该字符串

我尝试了各种方法,但是都给出了“获取非对象的属性”的相同错误

foreach($response->Product->$x as $prod)
{
print $prod->Name;
print $prod->Price;
print $prod->Stock;
print $prod->SupplierName;
print $prod->CategoryName;
$x++;
}

//但是我的响应字符串是

stdClass Object ( 
[Product] => Array 
( [0] => stdClass Object
( [Id] => 2 [Name] => Green Shirt [Price] => 1800 [Stock] => 50 [SupplierName] => Ali Yar [CategoryName] => Jeans )
  [1] => stdClass Object
  ( [Id] => 7 [Name] => Red Shirt with Flowers [Price] => 2200 [Stock] => 40 [SupplierName] => Ali Yar [CategoryName] => Shirt )
  [2] => stdClass Object
  ( [Id] => 8 [Name] => Red Shirt with Flowers [Price] => 2200 [Stock] => 40 [SupplierName] => Ali Yar [CategoryName] => Shirt ) 
  [3] => stdClass Object
  ( [Id] => 9 [Name] => Check Shirt Yellow [Price] => 1100 [Stock] => 200 [SupplierName] => Ali Yar [CategoryName] => Shirt 
  )
 )
 ) 

我遇到这些错误试图获取为foreach()提供的非对象属性和无效参数

2 个答案:

答案 0 :(得分:1)

您的代码不清楚,但我认为您必须在此编辑foreach

foreach($response->Product as $prod)
{
print $prod->Name;
print $prod->Price;
print $prod->Stock;
print $prod->SupplierName;
print $prod->CategoryName;
$x++;
}

答案 1 :(得分:1)

由于Product属性是数组,因此:

foreach($response->Product as $prod)
{

    print $prod->Name;
    print $prod->Price;
    print $prod->Stock;
    print $prod->SupplierName;
    print $prod->CategoryName;

    // this increment is useless
    //$x++;

}