仅通过键名来获取JSON中的特定键/值,而不是全部

时间:2016-12-13 20:10:20

标签: php arrays json multidimensional-array

我有JSON显示多个键值对。我想循环并创建一个只包含我想要的键值对的新数组,以便显示它们。这是我的尝试,但当然,我的代码重写了我的数组($new_array)只有一个元素。

 //SAMPLE JSON
 [{"PropertyId":"555","FloorplanId":"555","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"},{"PropertyId":"666","FloorplanId":"666","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"}]

 //GET ALL JSON FROM URL
 $json = file_get_contents('<URL>');
 $data = json_decode($json);
 // print_r($data); //ALL keys

 //GET JUST THE KEYS I WANT
 $new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");

 // Create new array
 foreach($data as $item) {
   $new_array['FloorplanName'] = $item->{'FloorplanName'};
   $new_array['Beds'] = $item->{'Beds'};
   $new_array['Baths'] = $item->{'Baths'};
 }

 //loop over $new_array
 foreach($new_array as $item) {
   $item->{'FloorplanName'};
   $item->{'Beds'};
   $item->{'Baths'};
 }

1 个答案:

答案 0 :(得分:1)

现在,您在$new_array上设置了关联键,并且每次都通过foreach循环覆盖您的数据。相反,您需要将项(子数组)添加到$new_array并将数据分配给子数组。

而不是:

//GET JUST THE KEYS I WANT
$new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");

// access property of object in array
 foreach($data as $item) {
   $new_array['FloorplanName'] = $item->{'FloorplanName'};
   $new_array['Beds'] = $item->{'Beds'};
   $new_array['Baths'] = $item->{'Baths'};
 }

你需要

$new_array = array(); // this array should be empty

// access property of object in array
foreach($data as $item) {
  $new_array[] = array(
    'FloorplanName' => $item->{'FloorplanName'},
    'Beds' => $item->{'Beds'},
    'Baths' => $item->{'Baths'},
  );
}

此外,要遍历新数组,您需要更改最终循环:

//loop over $new_array
foreach($new_array as $item) {
  echo $item['FloorplanName'];
  echo $item['Beds'];
  echo $item['Baths'];
}