How to visit an array indexed by indexed in php / Laravel? - php

I got an API response like
["at123#gmail.com","adhd5#gmail.com","adahsad5#gmail.com"]
I got this array in a request variable $request->optional_email I am trying to access data by a loop like below:
foreach ($request->optional_email as $key => $optionalEmail) {
$email->email = $optionalEmail[$key];
$email->save();
}
But it doesn't work. How can I solve it?

As the $request->optional_email is just a list you do not need to use the $key variable in the foreach.
Instead you should just use the value ($optionalEmail) of the foreach so your code would look something like this:
foreach ($request->optional_email as $optionalEmail) {
$email->email = $optionalEmail;
$email->save();
}

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.

Multidimensional array into POST call using foreach loop PHP

Looking for some advise with regards to multidimensional Arrays, pushing the vars into a POST call within a foreach loop.
I currently have a foreach loop containing an IF clause:
foreach ($responseData['data'] as $key => $value) {
if (strtotime($value['attributes']['created_time']) > $currentDateMinusThirtyMinutes) {
array_push($emails, $value['attributes']['email']);
}
}
This is supposed to fetch the Email for all arrays which meet the condition of being created in the last 30 minutes.
However, now i am stuck, I need to fetch multiple other variables and call on a POST call similar to the below:
https://developer.example.co.za/{$PAGE}/create?reference={$ID}&currency=ZAR&amount={$AMOUNT}&firstname={$FIRST}&lastname={$LAST}&email={$EMAIL}&sendmail=true
What i need to know is, is there a better way to treat the foreach loop?
Is foreach the right way to go?
In essence I would need to run through each of the $responseData['data'] returns and make a POST call to the above URL.
Any advise would be appreciated.
Fixed this by creating a Data_array which stored the values I required, then adding the POST call inside the foreach loop which then did the trick.
The foreach ended up looking like this:
foreach ($responseData['data'] as $key => $value) {
if (strtotime($value['attributes']['created_time']) > $currentDateMinusThirtyMinutes) {
$data_array[] = array(
"id" => $value['attributes']['id'],
***add rest of vars you want***
);
***Add POST call or whatever else you want to do***
}
}
Thanks #darklightcode for pointing me to the idea of splitting out just the variables I wanted.

Array of String values, not an array of object Strings

Basically I am calling an API to get an array of URLs for an image.
I start off by doing this
$mainResponse = array(
"result" => array(
),
"ack" => "success"
);
I will then make my call and add the image URLs like this:
foreach($resp->Item as $item) {
$picture = $item->PictureURL;
array_push($mainResponse['result'], $picture);
}
Finally, I will echo this out to me.
echo json_encode($mainResponse);
The problem I am facing is that my response is
{"result":[{"0":"IMAGE_URL","1":"IMAGE_URL"}],"ack":"success"}
Where I would want it to be like....
{"result":["IMAGE_URL","IMAGE_URL"],"ack":"success"}
Where did I go wrong in my PHP code?
Seems like $picture is a associative array, change the foreach loop with this:
foreach($resp->Item->PictureURL as $item) {
foreach($item as $_item){
array_push($mainResponse['result'],$_item);}
}
For some reason this API returns an object instead of an array.
You can just do:
foreach ($resp->Item as $item) {
$picture = $item->PictureURL;
array_merge($mainResponse['result'], (array)$picture);
}
You can use array_push if you want every item to have separate pictures.

PHP: String in json parse

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.

PHP - looping through an array of JSON Variables

I have the following array that is in PHP (this is a print_r() output).
I'm currently struggling to loop through this data - need to be able to process each part and access the values in each array item. How can I do this.
I've tried the following unsuccessfully...
foreach (array as $key => $value) {
echo $key;
}
Try this. Since you have an array of objects, you should be able to access each object property using ->
foreach($array as $value) {
echo $value -> userid;
}
It should echo out all the user id in that array of objects
You have an array of objects, so try something like this:
<?php
foreach ($array as $value) {
echo $value->userid;
echo $value->action;
echo $value->photo_name;
}
You don't need the $key since you're not using it in the loop. Each iteration will put the object in the $value variable, on which you can access it's properties.

Categories