如何在PHP中迭代JSON

时间:2015-07-16 21:14:36

标签: php json

在下面的JSON中,我想获取所有客户的电话并存储在一个数组中:

{  
   "MetaInformation":{  
      "@TotalResources":1,
      "@TotalPages":1,
      "@CurrentPage":1
   },
   "Customers":[  
      {  
         "@url":"https:\/\/URL/customers\/1",
         "Address1":"Mumbai",
         "City":"Mumbai",
         "CustomerNumber":"1",
         "Email":"xyz@gmail.com",
         "Name":"Saurabh Pradhan",
         "OrganisationNumber":"",
         "Phone":"91xxx",
         "ZipCode":"45153"
      }
   ]
}

我尝试使用以下但它一直让我犯错误“试图获取非对象的属性”:

$customer_json = json_decode($api->getAllCustomers());    
$customer_json->Customers[0]->Phone;

1 个答案:

答案 0 :(得分:-1)

问题是JSON对象的PHP表示不是对象。 PHP使用关联数组。为了方便使用行为:

$customer_json = json_decode($api->getAllCustomers(), true);
$customer_json['Customers'][0]['Phone'];