Multiple Objects in Foreach Loop - php

I have the following two foreach loops that are working for me:
foreach ( $pa_speciesreactivityabbrs as $pa_speciesreactivityabbr ) {
echo '<span>' .$pa_speciesreactivityabbr->name. '</span>';
}
foreach ( $pa_speciesreactivitys as $pa_speciesreactivity ) {
echo '<span>' .$pa_speciesreactivity->name. '</span>';
}
However I need to combine the $pa_speciesreactivityabbrs and $pa_speciesreactivitys in the same loop to output $pa_speciesreactivityabbr->name and $pa_speciesreactivity->name together.
I have gone through a number SO answers from other posts, but can't seem to apply them to my situation.

Looks like your objects are in normal arrays. Assuming you don't use associative arrays, you could do this easily by looping through one of them and output data from both at the same time. Like this:
foreach ($array1 as $index => $obj1) {
echo '<span>' . $obj1->name . $array2[$index]->name . '</span>';
}
I shortened the array names to make it more readable, but I'm sure you see how it works.

Related

PHP key() returning the key for the next item in the array, not the current one

The code here is pretty simple, so I'm not sure what could be happening. This site that I made a couple of years ago has been working fine the whole time, and today I randomly checked on it to find it completely borked. I'm not sure if it was a PHP upgrade performed by my webhost or maybe an automatic WordPress update that broke it, but in any case, the code is not behaving as expected.
In the WordPress loop, for each post, this code is running:
$stats = array(
'recon' => 'Recon',
'inf' => 'Infantry',
'fist' => 'Fire Support',
'atgm' => 'ATGM',
'armor' => 'Armor',
'arty' => 'Artillery',
'aa' => 'Anti-Air',
'air' => 'Aircraft',
'heli' => 'Helicopters'
);
foreach( $stats as $stat_name ):
$stat_key = key( $stats );
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
...
next( $stats );
endforeach;
As you can see on the live site, key( $stats ) is returning the key for the next item in the array and not the current one, and returning null for the last item in the array. What could possibly be going wrong here?
Simply make use of the key option in the foreach
foreach( $stats as $key => $stat_name ):
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
endforeach;
I wouldn't suggest calling, next while in a foreach loop, it will do the iteration for you. Likely it's already done so when you call key, because its moved the pointer on to the next item already.
Foreach can do weird things when you mess with the structure of the array because it creates a shadow copy of the array (I forget the exact way its explained, and they may have changed it somewhat in 7). In any case, I'm not sure what affect calling next will have, maybe none, because of the way that it handles iterating with foreach. I never tried it!
If you want to use next, then use the do or while loop.
The really proper syntax would be
foreach( $stats as $key => $stat_name ){
// DEBUG:
echo '<p>' . $stat_key . ' : ' . $stat_name . '</p>';
}
The Alternative syntax is useful if you have it in html, such as
<?php foreach( $stats as $key => $stat_name ): ?>
<p><?=$stat_key;?> : <?=$stat_name;?></p>
<?php endforeach; ?>
<div> ....
This is because the endforeach; is more descriptive then the } and it can be very easy to lose track of the } when mixed with HTML and other control structures (like if statements). With the alternative statement you wind up with things like endforeach; endif; instead of } } . Hope that makes sense.

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

Multiple Foreach loops for one array

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.

unserialize() value insert with serialize() of database.?

i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag <ul><li>...?
i have in database this: a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}
LIKE:
Coffee
Game Notes
Internet
Pool
You need to use unserialize(), as you said, with a foreach() loop, like this:
$arr = unserialize($dbString);
echo "<ul>";
foreach($arr as $key => $val)
{
echo "<li>$val</li>";
}
echo "</ul>";
This will echo a list containing value because foreach() iterates through the unserialize()d array, as you have specified in your question.
The $key => $part is the icing on the cake for foreach(); if you want the get the array key, simply reference $key. If you want the data for that key, use $val.
If you want to echo just one element (your example is Internet), just don't use a loop and reference it by key (integer):
$arr = unserialize($dbString);
echo $arr[2];
This echos the third element in the array on it's own.
Original question
Unserialize the data and loop over it printing it out. Notice that I have also added in checks to see that we are getting back an array and that it contains something before looping over it.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Internet
I think this is what you are asking for. To only echo out the value if its Internet.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
if('Internet' != $value) {
continue;
}
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
JSON
If you can I would stop using serialize and use json_encode instead. It is easier to encode and decode in more programming languages and it is easier to edit by humans should you need to update the DB directly.

PHP foreach array

I had to make some changes to my app to work with a relationship change in my db.
Originally I had whats below for a 1::0-1 relationship
if ($model->address->AddressLine1) echo $model->address->AddressLine1.'<br />';
if ($model->address->AddressLine2) echo $model->address->AddressLine2.'<br />';
if ($model->address->city->Name) echo $model->address->city->Name;
if ($model->address->city->regionCode->RegionCode) echo ', '.$model->address->city->regionCode->RegionCode;
but had to change it to work with a 1::0-n relationship
foreach ($model->address as $al1)
foreach ($model->address as $al2)
foreach ($model->address as $al2)
foreach ($model->address as $city)
foreach ($model->address as $region) {
echo $al1->AddressLine1.' '.$al2->AddressLine2.'<br/>'.$city->city->Name.' '.$city->city->regionCode->RegionCode;
}
I want to retain the functionality of the if in my original code. With the original code I was able to use
', '.
in
if ($model->address->city->regionCode->RegionCode) echo
', '. $model->address->city->regionCode->RegionCode;
to only add a comma after City only when a Region is present in the db.
So how can I get that back and utilize if within my array?
You only need one foreach loop — you're just iterating through a single array.
You can stick the conditionals into the foreach loop, updating the variable name. This assumes that $model->address is an array. On each iteration $address will be set to a subsequent element of that array.
foreach ( $model->address as $address ) {
if ($address->AddressLine1) echo $address->AddressLine1.'<br />';
if ($address->AddressLine2) echo $address->AddressLine2.'<br />';
if ($address->city->Name) echo $address->city->Name;
if ($address->city->regionCode->RegionCode) echo ', '.$address->city->regionCode->RegionCode;
}
For more information:
PHP foreach documentation
foreach tutorial

Categories