PHP: String in json parse - php

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.

Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

Related

How to put foreach in array

I have this
$homedata = $user->getbanks();
foreach ($homedata as $data)
echo json_encode(array("replies" => array(array("message" => $data->bankname))));
I have this put the result am getting is only one array from the list. I want to get all.
If I understand your requirement correctly, you need the banknames in an array replies within a key message. For that the below code will do the job. But you can optimize the query for better performance.
$homedata = $user->getbanks();
$banks['replies'] = [];
foreach ($homedata as $data) {
$banks['replies'][]['message'] = $data->bankname;
}
print_r(json_encode($banks)); exit;
Further, you were only getting the first content because you are overriding the previous content when you iterate using foreach.

Bug when trying to update an array

I have a two questions with a symfony's project.
My first one :
I am trying to modify some data in an array.
I have this code
var_dump($results); // FIRST ONE
foreach ($results as $result) {
foreach ($result as $res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
var_dump($res); // THIS ONE IS MODIFIED
}
}
var_dump($results); // LAST ONE... SAME AS THE FIRST ONE
I don't understand why my array ' $results ' is no updated... am i missing something ?
And my second question : is there any way to simplify this code ? I don't like the 3 foreach.
Thanks you guys :)
PHP foreach copy each item when iterate so $result array will not update when you change $res item.
1) You can use array keys to change main array
foreach($arrr as $k => $item) {arrr[$k]['key'] = 'changed'}
2) Or you can get link to the $res item and change it dirrectly
foreach($arrr as &$item) {$item['key'] = 'changed'}
Note that second case can cause different issues
Unless you're passing an object in PHP, PHP does not pass values by reference. $res is a copy of the value, not a link to the original value. If you know what you're doing, you can pass by reference. When passing by reference, altering $res would alter the original data. You pass by reference by prefixing a & to the variable or argument.
Since this is a nested foreach, you'll also have to pass $result by reference to avoid that being a copy of the item of $results.
foreach ($results as &$result) {
foreach ($result as &$res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
}
}

Creating arrays within arrays without creating keys first

This is how I used to create keys that didn't exist inside an array when looping through data:
$array = [];
foreach ($results as $result) {
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
$array[$result->id][] = $result->value;
}
A colleague at work does the following. PHP doesn't error but I am not sure if it's a feature of PHP or if it's incorrect:
$array = [];
foreach ($results as $result) {
$array[$result->id][] = $result->value;
}
Is it incorrect for me to do the above?
if condition you put in your code is unnecessary. Let me explain.
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
This mean if $array[$result->id] is not exist than you are define it as an array, however $array[$result->id][] it self create new array if not existing without throwing any error. So no need to use if condition error. In conclusion, both code are correct, just you are using unnecessary if condition.

How do you create an array from variables derived from a foreach loop?

I'm certain this is VERY simple, but being new and not knowing what I'm doing I can't quite get it on my own.
I am trying to create an array of wordpress post ID's that is derived from a simple foreach loop.
Basically I have this as my code:
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz ) {
$quiz_id_number = $single_quiz['quiz'];
$omit_these_quizzes[] = $quiz_id_number;
}
I would like to take each of the resulting $quiz_id_number 's and have then end up in array that looks like this:
$omit_these_quizzes = array(8195,8193);
However, I keep ending up with an array that only contains the variable from the very last foreach loop, instead of them all. What am I doing wrong?
Thanks!
Your code looks fine.But if you want alternative try this:
see here for in_array and array_push.
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz )
{
$quiz_id_number = $single_quiz['quiz'];
if(!in_array($quiz_id_number ,$omit_these_quizzes))
{
array_push($omit_these_quizzes, $quiz_id_number);
}
}
hope it's help you.
This work?
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz ) {
$quiz_id_number = $single_quiz['quiz'];
array_push($omit_these_quizzes, $quiz_id_number);
}
Looks like you are creating a new array in each loop, that's why you end up with an array containing just a single element...
Use:
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz )
{
$quiz_id_number = $single_quiz['quiz'];
array_push($omit_these-quizzes, $quiz_id_number);
}
Your code is correct. Inspect your $filtered_pass variable by calling var_dump($filtered_pass); may be it contain only one subarray.

foreach results as feed_url

I'm trying to get the result of my foreach loop into an url to do a simplexml_load_file with.
So it goes like this:
(...) //SimpleXML_load_file to get $feed1
$x=1;
$count=$feed1->Count; //get a count for total number of loop from XML
foreach ($feed1->IdList->Id as $item1){
echo $item1;
if($count > $x) {
echo ',';} //Because I need coma after every Id, except the last one.
$x++;
}
The two echo are just to see the result. It gives me something like:
22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843
I would like to put that in a url to make a simplexml_load_file just like that
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';
So it would look like:
$feed_url = 'http://www.whatevergoeshere22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843someothertext';
I've try to store it into an array or a function and then call it into the feed_url but it did not work the way I tried it.
I hope it's clear, I'll answer fast to questions if not.
Thanks.
It's really difficult to make out what you want, so I'm going to guess you want to store the list as a comma delimited string in a variable. the easiest way is to implode the array of ids
$ids = array();
foreach ($feed1->IdList->Id as $item1){
$ids[] = (string) $item1;
}
$RESULT_OF_FOREACH = implode(',', $ids);
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';

Categories