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}¤cy=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.
Related
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.
I am working on a WordPress plugin for a specific theme but have a general question,
I have an array and want to do something with each object and return the result.
everything is Ok but the "foreach" only works for the first object of array and I think its because of "return" but for some reasons I cannot use "echo" instead of return.
this is my code:
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field = get_field($value);
}
return $user_field;
}
I have read other similar topics but passing the variable to another function to do the "return" job for me also not works
Your doubt: the "foreach" only works for the first object of array and I think its because of "return"
No this not for return it's because of variable overwriting inside the foreach() loop every time. Actually you're not returning only the first element, here you're returning the last element because you're overwriting $user_field variable every time within foreach() loop
Try instead to push result to it using $user_field[] and then you're good to go
$cast_list = array(
"composite_cast",
"graphic_designer_cast",
"product_manager_cast",
"render_cast",
"the3d_cast",
"story_board_cast"
);
foreach ($cast_list as $value)
{
$user_field[] = get_field($value);
}
return $user_field;
All the functions work until the return keyword. You need to create a new array and append all the edited elements to it and then return it.
$user_fields = array();
foreach ($cast_list as $value)
{
array_push($user_fields, get_field($value));
}
return $user_fields;
Or you even can work on each field right in the loop and return nothing.
I have this object containing one row and many keys/variables with numbered names.
I need to pass each of them one at a time to another function. How do I loop through the keys instead of the rows?
The code would look like this:
foreach ($object['id'] as $row):
$i++;
$data['myInfo'][$i] = $this->get_data->getInfo('data1', 'id', $row->{'info'.$i.'_id'});`
but this obviously won't work since it's looping through the rows/instances of an object, and I have only one row in my $object['id'] object (with info1_id, info2_id, info3_id, info4_id... etc keys), so the loop stops after just one cycle. And I really don't feel like typing all of that extra code by hand, there's gotta be solution for this. :)
You can just iterate through your object like an array :
foreach ($object['id'] as $row) {
foreach ($row as $k => $v) {
$id = substr($k, 4, strpos($k, '_')-4);
$data['myInfo'][$id] = $this->get_data->getInfo('data1', 'id', $v);`
}
}
Thanks for the directions Alfwed, I didn't know you could use foreach loop for anything other than instances of an object or arrays (only started learning php a week or so ago), but now it looks pretty straight forward. that's how I did it:
foreach ($object['id'] as $row):
foreach ($row as $k=>$v):
$i++;
if ($k == print_r ('info'.$i.'_id',true)){
$data['myinfo'][$i] = $this->get_db->getRow('products', 'id','info'.$i.'_id');
<...>
in my case, I knew how many and where were those values, so I didn't have to worry about index values too much.
Here is a fairly big object dumped using print_r.
https://docs.google.com/document/d/175RLhWlMQcyhGR6ffGSsoJGS3RyloEqo4EEHCL2H2vg/edit?usp=sharing
I am trying to change the values of the uploaded_files.
Towards the end of that object you'll see something like
[uploaded_files] => Array
(
[attachment] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Central-Coast-Montessori-logo.jpg
[attachment2] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Andrew.jpg )
My code
// move the attachments to wpcf7ev temp folder
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
$new_filepath = WPCF7EV_UPLOADS_DIR . '/' . basename($uploaded_file_path);
wpcf7ev_debug("New file path is {$new_filepath}");
rename($uploaded_file_path, $new_filepath);
wpcf7ev_debug("'{$key}'is the KEY for {$uploaded_file_path}");
wpcf7ev_debug($cf7ev_object['uploaded_files']);
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
}
To loop through it I have been using
foreach ($cf7ev_object->uploaded_files as $key => $uploaded_file_path) {
and this has worked.
But shouldn't it be
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
? As '->' is for accessing methods?
And specifically I want to update the values of those uploaded_files, so to do that I need to do
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
? But this doesn't seem to be working.
I think I need to be clear on how to access values in an object.
Thanks.
First of all, regarding the single arrow "->" that is how you reference an objects values. But I won't get into that. Since you say it works, $cf7ev_object is obviously an object.
You say you want to "access the values in the object".
var_dump($cf7ev_object);
This will spit out what is in that object. I gather you are a bit of a newbie, so I will try to help you out best I can with the limited data you provided (you may want to expand your question.
Looping is not a one-shot deal. You can have nested loops and nested loops inside of those. However, it is a resource hog if you're not careful. Here is an exercise that might help you.
$new_array = array();
foreach($cf7ev_object->uploaded_files as $key => $value) {
$new_value = $value;//do something to the $value here
$new_array[$key] = $new_value;
}
//take a look at your work now:
print_r($new_array);
I hope this helps. Note: your google doc is restricted, public can't see it.. And your question is too vague. Let me know if I can help more.
If you want to change the object array values instantly you just set it equal to the above loop result:
$cf7ev_object->uploaded_files = $new_array;
I've been looking into this problem for a couple of days now and I just can't seem to figure it out.
I'm trying to do something simple, I thought, just looping through an array.
This is a screenshot of the array: http://cl.ly/image/3j2J3x1C3B0j
I'm trying to loop through all the 'Skills' array, there the "Skill' array and inside that grabbing the "Icon".
For this I made 2 loops:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills as $skill)
{
//print_r($skill['skill']);
}
}
Unfortunaly this doesn't work, in laravel. I'm getting the "Undefined index: skill" error. It does work when I tried it outside , as a standalone script.
Out side both of the loops I can select the icon with:
print_r($hero_data['skills']['active'][0]['skill']['icon']);
I'm sure I'm overlooking something stupid...
Thanks a lot for the help,
Looking at what you've said from the other solutions posted here, it's clear that you are looping through the sub arrays and not all of those sub arrays contain the keys that your further loops are looking for.
Try this:
foreach ($hero_data['skills']['active'] as $skills) {
if (isset($skills['skill']['icon'])) {
print_r($skills['skill']['icon']);
}
}
Because, for example, if $hero_data['skills']['active'][8] doesn't actually have a skill array or a ['skill']['icon'] array further down, then the loop will throw the errors you have been reporting.
The nested array keys you are looking for must be found in every iteration of the loop without fail, or you have to insert a clause to skip those array elements if they aren't found. And it seems like your $hero_data array has parts where there is no ['skill'] or ['icon'], so therefore try inserting one or more isset() checks in the loops. Otherwise, you need to find a way of guaranteeing the integrity of your $hero_data array.
Your game looks interesting by the way!
Inside skills you have an 'active' attribute and it contains the array you need, so you need to change your code to this:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills['active'] as $skill)
{
//print_r($skill['skill']);
}
}
Try:
foreach ($hero_data['skills'] as $skills)
{
foreach ($skills as $skillState)
{
foreach ($skillState as $skill)
{
print_r($skill['skill']);
}
}
}
You simply need to iterate the active index of the array. this should work :
foreach ($hero_data['skills']['active'] as $skills) {
print_r($skills['skill']['icon']);
}