PHP foreach array - php

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

Related

Manage a 4 dimensional array or a 5 dimensional with foreach statement in php

I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.
A very simple example below
$documents = array(
array(
"name"=>"Markos",
"lastname"=>"papadopoulos",
"country"=>"Greece",
"nationality"=>"greek",
"job"=>"web developer",
"hobbies"=>array(
"sports"=>"boxing",
"others"=>array(
"freetime"=>"watching Tv"
)
)
)
);
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
echo $key." ".$value."<br>";
foreach ($value['others'] as $subkey=>$subvalue){
echo $subkey['freetime'];
}
}
}
I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.
foreach ($documents as $key) {
echo $key['name']. '<br>';
echo $key['lastname']. '<br>';
echo $key['country']. '<br>';
echo $key['nationality']. '<br>';
echo $key['job']. '<br>';
echo $key['hobbies']['sports']. '<br>';
echo $key['hobbies']['others']['freetime']. '<br>';
}
output will be
Markos
papadopoulos
Greece
greek
web developer
boxing
watching Tv
In PHP, foreach actually have two syntaxes:
foreach($array as $element) this might means $element ends up being an array
foreach($array as $key => $value) this means that key will never be an array, it is what the key, so what you have before the => in your array, while $value can be an array.
Here is the way to follow the first syntax, mind that you don't even have to nest foreach here, as pointed out by #Nathanael's comment what you have in your array is mostly scalar, not really nested arrays.
foreach($documents as $document){
echo $document['name']."<br>".
$document['lastname']."<br>".
$document['country']."<br>".
$document['nationality']."<br>".
$document['job']."<br>".
$document['job']."<br>".
$document['hobbies']['sports']."<br>".
$document['hobbies']['others']['freetime'];
}
If you want to go in the second syntax, then it would be even better to make a recursion:
function display_multi_level_array($array) {
foreach($array as $key => $value){
if(is_array($value)) {
display_multi_level_array($value);
continue;
}
echo $key." ".$value."<br>";
}
}
display_multi_level_array($documents);
try
foreach($documents as $document){
echo $document['name']."<br>"
.$document['lastname']."<br>"
.$document['country']."<br>"
.$document['nationality']."<br>"
.$document['job']."<br>";
foreach ($document['hobbies'] as $key=>$value){
if (is_array($value)) {
foreach ($value as $subkey=>$subvalue){
echo $subvalue;
}
} else {
echo $key." ".$value."<br>";
}
}
}

Multiple Objects in Foreach Loop

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.

How to retrieve array element one by one in PHP?

Hi am trying to read a directory for html files and put them in array and retrieve one by one.
i used following code
$filelist = glob($directory."/*.html");
$val=natsort($filelist); // Sort the array
foreach($filelist as $key => $value)
{
echo " $value , ";
}
$next=0;
$ns=$next+"1";
$filelist1=$filelist[$ns];
echo $filelist1;
am getting html files in a array but not able to retrieve one by one
please suggest
Thanks
That's echoing each item, not returning an array. Maybe it would be more clear if you change
echo " $value , ";
to
echo "ITEM $value ENDITEM , ";
Works for me
$directory = "./dir";
$filelist = glob($directory."/*.html");
sort($filelist);
foreach ($filelist as $filename) {
echo "$filename, ";
}
Also you may use
echo implode(', ', $filelist);
Instead of foreach
Return result like this:
./dir/christmas_en.html, ./dir/christmas_fr.html, ./dir/etpl_winphone.html,

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 : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

Categories