Omar
Omar

Reputation: 806

Get only specific key/values from JSON by key names not all

I have JSON that shows multiple key-value pairs. I'd like to loop through and create a new array with only the key-value pairs I want in order to display them. This is my attempt, but of course, my code is re-writing my array ($new_array) to have only one element.

 //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'};
 }

Upvotes: 2

Views: 2107

Answers (1)

elixenide
elixenide

Reputation: 44841

Right now, you set associative keys on $new_array and overwrite your data each time through your foreach loop. Instead, you need to add an item (a sub-array) to $new_array and assign the data to the sub-array.

Instead of this:

//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'};
 }

You need

$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'},
  );
}

Also, to loop through the new array, you need to change your final loop:

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

Upvotes: 2

Related Questions