PHP - Duplicate <li>'s on foreach - php

i dont speak english but i will try get it.
My problems is on foreach ($json->mods->$k as $name) { because i'm getting duplicates <li>:
Heres the example:
<ul id="1">
<LI><B>BR:</B>
<LI><B>BR:</B>
<LI><B>BR:</B> Asterixmod, Explanado, Modquack</li>
<br>
<LI><B>DE:</B> Sweetphoenix</li>
<br>
<LI><B>E2:</B>
<LI><B>E2:</B> Irishcow, Welshnutter</li>
</ul>
CODE:
<?php
echo '<ul id="1">';
$link = '.json';
$f = file_get_contents($link);
$json = json_decode($f);
if (empty($json)) {
echo '<li id="ere"><B>ERROR</B></li>';
} else {
foreach ($json as $key => $val) {
foreach ($val as $k => $v) {
foreach ($json->mods->$k as $name) {
echo strtoupper('<li><b>' . $k . ':</b> ');
}
echo(implode(', ', $json->mods->$k));
echo '</li><br>';
}
}
echo '</ul>';
}
Hope anyone help me, ty.

The reason you're getting this error is because inside your foreach ($json->mods->$k as $name) you are opening an <li>, however, you're not closing it until after that loop. This means that eg. BR will have 3 opening tags and one closing tag.
Furthermore, you can get the output you want with just 1 loop:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ';
echo implode(', ', $val);
echo '</li><br>';
}
or you could even make the echo one line:
foreach ($json->mods as $key => $val) {
echo '<li><b>' . strtoupper($key) . ':</b> ' . implode(', ', $val) . '</li><br>';
}
Hope this helps!

Related

For Each loop with 2 parent 'columns'

I am trying to expand on some working code, and not sure how to do it.
Basicly the information can be under either information or some othertitle.
but i dont care for this split, i just want to do a foreach for all of them together.
Basicly i currently run a for each loop like this:
foreach ($info_array['information'] as $item) {... do something }
Would it be possible to somehow say, For each info_array 'information' & 'othertitle' as $item?
array is structured like:
information
random number
price
amount
total
random number
price
amount
total
othertitle
random number
price
amount
total
random number
price
amount
total
i tried this, but that didnt work:
foreach ($item_array['information'] as $item and $item_array['othertitle'] as $item)
The first idea that comes in mind is just use two loops - first one iterates over $item_array['information'], second one - over $item_array['othertitle']. Something like this:
foreach ($item_array['information'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
foreach ($item_array['othertitle'] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
But, if you do the same output for each element of each array, you can do this:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
echo $item['key1'] . ' -> ' . $item['key2'];
}
}
And even it the output for arrays is different - you can solve it in this way:
$keys = ['information', 'othertitle'];
foreach ($keys as $key) {
echo 'Key is ' . $key . '<br />';
foreach ($item_array[$key] as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
And if you have to iterate over all subarrays of $item_array, the solution is the same as in #AbraCadaver answer:
foreach ($item_array as $key => $items) {
echo 'Key is ' . $key . '<br />';
foreach ($items as $item) {
if ('information' === $key) {
echo 'Info: ' . $item['key1'] . ' -> ' . $item['key2'];
} else {
echo 'Ttile: ' . $item['key1'] . ' and ' . $item['key2'];
}
}
}
Since you know the indexes you could array_merge or use +:
foreach ($item_array['information'] + $item_array['othertitle'] as $item) {
// do something
}
Otherwise you need two loops:
foreach ($item_array as $array) {
foreach($array as $item) {
// do something
}
}

How to remove first element of an array using loop

I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);

I'm Trying to format the output of an array using php

I'm Trying to format the output of an array using php but I can't seem to get the keys and values on the same line. I've listed the code that I'm using to display the keys and values but this code outputs the keys and values on different lines
function olLiTree($tree)
{
echo '<pre>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<pre>', $key ;
olLiTree($item);
echo '</pre>';
} else {
echo '<pre>', $item, '</pre>';
}
}
echo '</ul>';
}
print(olLiTree($results));
Use <ul> <li> .... </li></ul>. Also remove comma(,) because PHP use dot(.) for concat string.
function olLiTree($tree)
{
echo '<ul>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<li>'. $key ;
olLiTree($item);
echo '</li>';
} else {
echo '<li>' .$item. '</li>';
}
}
echo '</ul>';
}
print(olLiTree($results));
You use comma , instead of dot .
for string concatenation php use dot
function olLiTree($tree)
{
echo '<pre>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<pre>'. $key ;
olLiTree($item);
echo '</pre>';
} else {
echo '<pre>' . $item. '</pre>';
}
}
echo '</ul>';
}
print(olLiTree($results));

Php Multidimensional array for navigation

Needed Navigation Html
Home
Pages
About
Services
Products
Contact
FAQs
Sitemap
Privacy Policy
Column Layouts
1 Column
2 Column (Left Sidebar)
2 Column (Right Sidebar)
3 Column
4 Column
I want to use php arrays and foreach loops to output the needed html.
The php code I have thus far is:
<?php
$data = array("navigation");
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
echo '<ul>';
foreach($data as $nav) {
foreach($nav as $subNavKey => $subNavHref) {
echo "<li><a href='$subNavHref'>$subNavKey</a>";
}
}
echo '</ul>';
?>
I was thinking I would need three foreach loops nested but php warnings/errors are generated when the third loop is reached on lines such as:
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
I'm not quite sure how to test for 3rd level depths such as:
$data['navigation']['Pages']['About'] = base_url('pages/about');
Also, outputting the needed li and ul tags in the proper positions has given me trouble aswell.
Use recursion
$data['navigation']['Home'] = base_url();
$data['navigation']['Pages'] = base_url('pages');
$data['navigation']['Pages']['About'] = base_url('pages/about');
$data['navigation']['Pages']['About']['Team'] = base_url('pages/team');
$data['navigation']['Pages']['About']['Team']['Nate'] = base_url('pages/nate');
echo "<ul>"
print_list($data);
echo "</ul>"
function print_list($menu) {
foreach($menu as $key=>$item) {
echo "<li>";
if(is_array($item)) {
echo "<ul>";
print_list($item);
echo "</ul>";
} else {
echo "<a href='{$val}'>$key</a>";
}
echo "</li>";
}
}
<?php
function nav($data) {
$html = '<ul>';
foreach ($data as $k => $v) {
if (is_array($v)) {
$html .= "<li>$k" . nav($v) . "</li>";
}
else {
$html .= "<li><a href='$k'>$v</a>";
}
}
$html .= '</ul>';
return $html;
}
echo nav($data);
A recursive function can get the job done:
$items = array(
"Home",
"Pages" => array(
"About",
"Services",
"Products",
"Contact",
"FAQs",
"Sitemap",
"Privacy Policy",
"Column Layouts" => array(
"1 Column",
"2 Column (Left Sidebar)",
"2 Column (Right Sidebar)",
"3 Column",
"4 Column"
)
)
);
function getMenu($array) {
foreach($array as $key => $value) {
if(is_array($value)) {
echo "<li>" . $key . "</li>";
echo "<ul>";
getMenu($value);
echo "</ul>";
} else {
echo "<li>" . $value . "</li>";
}
}
}
echo "<ul>";
getMenu($items);
echo "</ul>";
Output:
You should use a recursive function, for example (Working Demo):
function makeMenu($array)
{
$menu = '';
foreach($array as $key => $value) {
if(is_array($value)) {
$menu .= '<li>' . $key . '<ul>' . makeMenu($value) . '</ul></li>';
}
else {
$menu .= "<li><a href='". $value ."'>" . $value ."</a></li>";
}
}
return $menu;
}
Then call it like:
$data = array(
"Home",
"Pages" => array("About", "Services"),
"Column Layouts" => array("1 Column", "2 Column (Left Sidebar)")
);
echo '<ul>' . makeMenu($data) . '</ul>';

Nesting foreach with data from multidimensional array

I have a multi dimensional array with the structure:
Name
Address
Area
Area Type 1
Area Type 2
Area Type 2
I have a loop that grabs the Name and Address for each business and echos them out. Now what I want to be able to do is now grab the area and chuck that out for each business. My loop thus far is as follows:
foreach ($data AS $key => $value) {
echo '<ul>';
echo '<li>';
echo $value['Name'];
echo '</li>';
echo '<li>';
echo $value['Address'];
echo '</li>';
echo '<li>';
foreach ($data as $row) {
echo $data['Area'];
}
echo '</li>';
echo '</ul>';
}
I can output all the Areas in one go with:
foreach($data as $row)
{
foreach($row['Area'] as $areaout)
{
echo $areaout;
}
}
But I need it to echo out with it's respective name and address
Shouldn't you simply replace
foreach ($foo as $row) {
echo $foo['Area'];
}
by
echo '<ul>';
foreach ($value['Area'] as $v) {
echo '<li>' . $v . '</li>';
}
echo '</ul>'
?

Categories