Multiple Foreach loops for one array - php

I have a foreach loops for an array called $feedsMerged. I have this foreach loop near the top of a document and it's setting some global variables from the array.
I'd like to recall the foreach loop, or run it again on that array and this time build elements from the variables I set above.
Top of the document.
foreach ($feedsMerged as $posts) {
$post_id = $post['post_id'];
etc etc
}
Then bottom of page
foreach ($feedsMerged as $posts) {
echo '<div class="' . $post_id . '">stuff</div>';
}
Is this possible to do? The reason for using two foreach loops on the same array is I'd like to keep this all organized and I'll have content in between each foreach that can't be in this foreach

No problem at all. You can access an array as many times as you like using any supported method in a script.

Related

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.

Remove an element from an array within a foreach loop *without* using $key = > $val

I'm working in PHP and I'm trying to loop through an array, and in certain circumstances, delete the particular element of the array.
I've seen multiple questions similar to this, but the answers always involve using $key = $val in the foreach. I just have &$element. This is a relatively large loop, and switching to $key => $value would require a lot of rewrite and testing; so I'm hoping there's a way to do it with the referenced element. (Basically there are a lot of different things that can happen depending on the value of the element. Removal is just one of many possibilities.)
Note that I am using $element by reference, not value. I would swear this used to work, but it's not working now (maybe broke when I moved from PHP 5 to 7 ?)
So...
foreach( $things as &$element ) {
...
if( $element == 'hello' ) {
unset( $element );
}
...
}
Is there a way to make this work using &$element ?
$value is just the variable you assign the value to; is arbitrary name. So you can use $key=>$value and your &$element reference together.
foreach ($things as $key => &$element) { /* .. */ }

Loop through nested arrays PHP

Im trying to loop through PHP arrays decoded from a json file. I get the results but it only gives me the first results of the arrays in the the file. How can I make it loop? This is my code:
foreach ($events as $event) {
echo $event['d']['Tree1'][0]['Tree2']['Field1'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field2'] . '<br>';
echo $event['d']['Tree1'][0]['Tree2']['Field3'] . '<br>';
}
Sounds like you're trying to loop through the values of a "multidimensional array". You're starting correctly by going through your array with a loop, but then you're stuck because each element in your loop is... another array. So, to echo out the values of the child array, you want to run a second loop inside of your loop. Essentially, if your loop hits a child array, you want to loop through that array too. If you know your array is made of child arrays only, you can do this like so:
<?php
foreach ($events as $event) {
foreach($event as $ev) {
echo $ev;
}
}
If you need the keys, that adds a slight layer of complexity, but nothing you can't manage.
<?php
foreach ($events as $event) {
foreach ($event as $k=>$v) {
echo $k .': '. $v;
}
}
There are some examples in the php manual as well. You can also add in conditionals if you only need data from specific keys. Good luck!

How to use multiple condition in one foreach loop?

Can I do this- "foreach($products as $product && $categories as $category)". multiple condition in one foreach loop? If not then how do I proceed this?
Use two loops:
foreach ($products as $product) {
foreach ($categories as $category) {
// using $product and $category
}
}
I had the same question today as the OP. I figured I can split up the problem by first merging the two arrays and then performing the actual foreach loop on the combined array.
This is the idea:
$combined_array = $products + $categories
foreach ($combined_array as $items) {. . .}
Practically speaking, I split the problem into two foreach loops, the first for the merging of the arrays and the second for the actual algorithm.
And indeed it does save me alot of space! Since it is much shorter to append one array to another array than to repeat a complicated foreach algorithm on two separate arrays consecutively.
If your two arrays have the same length, just use a for loop instead and access the elements using the current index.
You just have to make sure, that the indezies are matching in the two arrays.
Its not possible to achieve what you are trying using a foreach loop.
for ($i = 0; $i < count($arr1); $i++) {
// do whatever you want with $arr1[$i] and $arr2[$i]
}
If your array have the same length, but the indizies may differ and you still want them to be on par, use array_values() before the loop to reindex both arrays.
This will only work for index based arrays!
you can't do that.
but what can you do is to loop inside the loop
foreach($categories as $category)
{
foreach($products as $product)
{
}
}
foreach( $codes as $code and $names as $name ) { }
That is not valid.
You probably want something like this...
foreach( $codes as $index => $code ) {
echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}

PHP - Looping through an object keys, one cycle per key

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.

Categories