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

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

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

Related

Laravel 5.2 get value field only in json response

Here is my code
$temp = $this->whereBetween('id', [$sid,$eid])
->select('id','temperature')
->get();
will return
[{"id":1,"temperature":34.5},{"id":2,"temperature":32.56},
how do i get only result like this, remove the key and pass the value only.
[{1,34.5},{2,32.56}]
I have using lists but it only return partial or all field.
You need to rebuild the array. I've tested this code and it works:
$array = [];
foreach($temp as $k => $v) {
$array[] = [$v['id'], $v['temperature']];
}
After that just serialize this array or use as is.
The function that you search, is array_values.
Iterate over your array, use that function, and save it back to an array.
For example:
$newArray = array();
foreach ($temp as $row) {
$newArray[] = array_values($row);
}

Inserting shifted array back into multidimensional array

So far I have a multidimen array results
foreach ($votes as $vote) {
$choices = array();
Foreach ($vote->getVoteChoicesOrdered() as $choice) {
array_push($choices, $choice->getAnswer()->getID());
}
array_push($results, $choices);
}
Later, I want to remove the first element of each choice in results and shift the positions back up (so I can remove the next element at [0] if I need to)
foreach ($results as $res) {
if (in_array(array_values($res)[0], $losers)) {
$shiftedRes = array_shift($res);
}
}
$losers is an array of array keys
Now that I have the shifted array, how would i go about replacing the current $result element with the new $shiftedRes? Something like $results[key($res)] = $shiftedRes?
Instead of shifting from your $res array, do it directly from the $results array.
foreach (array_keys($results) as $key)
{
if (in_array(array_values($results[$key])[0], $losers))
{
$shiftedRes = array_shift($results[$key]);
}
}

How to create an empty 2d array and assign values to it in PHP?

I have created an empty 2d array:
multiArray = array(array());
I wanted to add items to the 2d array using a foreach statement, such that for each item, add all the items of a second array that correlate to it. This would build my 2d array. I am going about it as such:
# The following variables are prepopulated with items
# $array1, my first array of items
# $array2, my second array of items
foreach ($array1 as $item1) {
foreach ($array2 as $item2) {
if ($item2['marker'] === $item1['marker'] { //item2 belongs to item 1 and thus needs to be added to the 2d array
$mulitArray[][] = [$item1][$item2];
}
}
}
That is not working though logically it seems sounds, but the PHP doesn't like that $mulitArray[][] = [$item1][$item2].
My expected output would be a 2d array that would show for each item1, all the item2s that match.
Thanks in advanced.
Maybe something like this.
$multiArray = array();
foreach ($array1 as $item1) {
$a = array();
foreach ($array2 as $item2) {
if ($item1['marker'] == $item2['marker']) {
$a[] = $item2;
}
}
$multiArray[] = $a;
}

How to declare, insert and iterate a php associative array with an associative array as value?

I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');

Adding an item to an associative array

//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
Before for loop:
$data = array();
Then in your loop:
$data[] = array($catagory => $question);
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question

Categories