So here is my code. The problem I am having is that I want the number from HP in my PHP code into my HP HTML code and the same thing with Cylinders. I have figured out the other stuff but when it comes to that part I am stuck
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" =>
array(
"HP" => 390,
"Cylinders" => 12
),
),
);
?>
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?></li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b></li>
<li><b>Cylinders:</b></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
I have a few concerns:
You lose the brilliance/utility of an associative array when you hardcode values into your script that you could otherwise just call from the array.
I don't like the look of the mid-list <div>. I can't think of any good reason to break up your unorder list flow with it.
I don't like the floating sub-list either. It logically belongs to Engine and good markup would dictate that the sub-list exist inside of its parent.
Here is what I would suggest considering my above points...
*Some Notes:
I'm not sure how you want to layout multiple lists as your array grows in size.
The echoing is just my personal preference. You can bounce in and out of php if you like.
ucfirst() allows you to avoid hardcoding the keys.
My snippet will make your task clean, DRY, and concise.
Code: (Demo)
$cars = array(
array(
"car" => "Ferrari",
"model" => "Testarossa",
"gearbox" => "Manual 5 Shift",
"designer" => "Battista Pininfarina",
"engine" => array(
"HP" => 390,
"Cylinders" => 12
)
)
);
foreach($cars as $details){
echo "<ul style=\"margin-bottom:10px;\">";
foreach($details as $key=>$item){
echo "<li><b>",ucfirst($key),":</b>";
if(!is_array($item)){
echo " $item</li>";
}else{
echo "<ul>";
foreach($item as $subkey=>$subval){
echo "<li><b>$subkey:</b> $subval</li>";
}
echo "</ul>";
echo "</li>";
}
}
echo "</ul>";
}
Source Code Output:
<ul style="margin-bottom:10px;">
<li><b>Car:</b> Ferrari</li>
<li><b>Model:</b> Testarossa</li>
<li><b>Gearbox:</b> Manual 5 Shift</li>
<li><b>Designer:</b> Battista Pininfarina</li>
<li><b>Engine:</b>
<ul>
<li><b>HP:</b> 390</li>
<li><b>Cylinders:</b> 12</li>
</ul>
</li>
</ul>
Rendered Output: (run my snippet # phptester.net to see this)
From you example, it seems to me that the list is static and consists of two elements, then you need not use forEach at all.
<?php foreach($cars as $cars_key => $car_val): ?>
<ul>
<div style="margin-bottom: 10px;">
<li><b>Car:</b> <?php echo $car_val["car"]; ?></li>
<li><b>Model:</b> <?php echo $car_val["model"]; ?></li>
<li><b>Gearbox:</b> <?php echo $car_val["gearbox"]; ?></li>
<li><b>Designer:</b> <?php echo $car_val["designer"]; ?>
</li>
<li><b>Engine</b></li>
<ul>
<li><b>HP:</b><?php echo $car_val["engine"]["HP"]; ?></li>
<li><b>Cylinders:</b><?php echo $car_val["engine"]["Cylinders"]; ?></li>
</ul>
</div>
</ul>
<?php endforeach; ?>
If you do need to use a nested forEach, here is how you would go about doing that:
foreach($cars as $cars_key => $car_val):
if($cars_key == "engine")
foreach($car_val["engine"] as $engine_key => $engine_val):
echo $engine_key.$engine_val;
endforeach;
endforeach;
Related
I am trying to turn this link into a php foreach loop without success and new to Stack overflow. I have used an array to generate the code but unsure how to turn this code into a foreach loop
<ul class="nav navbar-nav navbar-nav-first">
<li>About</li>
</ul>
I am just wondering how to create the li code for the foreach loop
foreach ($navItems as $item) {
echo "<li>$item[title]</li>";
}
<?php
$array = array(
"Home" => array("link" => "#home", "title" => "Take me home!"),
"About" => array("link" => "#about", "title" => "Learn more about us")
);
?>
<ul class="nav navbar-nav navbar-nav-first">
<? php
foreach ($array as $navTitle => $data) {?>
<li>
<?php echo $navTitle?>
</li>
<?php } ?>
</ul>
<?php $items = array( 'About' => 'about' ); ?>
<ul class="nav navbar-nav navbar-nav-first">
<?php foreach ( $items as $i_name => $i_ref ): ?>
<li><?= $i_name ?></li>
<?php endforeach; ?>
</ul>
please try
echo "<li><a href='".$item['slug']."' class='smoothScroll'>".$item['title']."</a></li>";
I am an absolute beginner in PHP.
I have a file main.php where I have a call to a php function:
<div id="navigation">
<nav>
<?php echo navigation('exclude'=>array('/about.php')) ?>
</nav>
</div>
I have a file navigation.php which is required in main.php, it has a small constructor to build the right structure of the navigation, it looks like this:
<ul class="navi naviTop">
<?php foreach($page as $key=>$singlepage){
if(!isset($singlepage['submenu'])){ ?>
<li class="navIem <?php echo $singlepage['name'];?>">
<a href="<?php echo $key; ?>">
<?php echo $singlepage['name'];?>
</a>
</li>
<?php } else { ?>
<ul class="hasSubs">
<?php foreach($singlepage['submenu'] as $subkey=>$subpage){ ?>
<li class="navItem subitem">
<a href="<?php echo $subkey; ?>">
<?php echo $subpage['name'];?>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php } ?>
</ul>
This works completely fine for me, but I want to have some options, that's why I establish a function:
function navigation($arguments=array()){
$defaults = array(
'class' => '',
'exclude'=> array()
);
$opts = array_merge($defaults, $arguments);
What is the right way for me to return this HTML structure that I generate by calling the navigation function?
To keep your code clean, you should seperate the template (html) from the business logic (php). Therefore your approach is great. Here 's a short example, how you could solve your issue.
First think about all the data you want to use in your function. As far as we can see, you need the pages and the options. Both arguments are arrays.
function navigation(array $pages = [], array $options = [])
{
$defaults = [
'class' => '',
'exclude' => [],
];
$options = array_merge($defaults, $options);
include __DIR__ . '/templates/navigation.phtml';
}
As you can see, the function does nothing more, as you have defined already. It takes another array parameter, where the pages are stored in. At the end of the function it includes the navigation template. There 's nothing more to do in PHP side.
The template navigation.phtml should look something like you already have.
<ul class="navigation<?php if (!empty($options['class'])):?><?= $options['class'] ?><?php endif; ?>">
<?php foreach ($pages as $url => $page): ?>
<?php if (!in_array($url, $options['excludes']): ?>
<li><?= $page['name'] ?></li>
<?pgp endif; ?>
<?php endforeach ?>
</ul>
I 've shortened the code example. To keep the logic in your template as small as possible you could filter the exluded pages before in your function to avoid the in_array if condition in your template.
In your main.php file, you can simple call the navigate function.
<nav>
<?php navigation($pages, $options) ?>
</nav>
The $pages and $options variables have to be declared before the call of the navigation function.
I need give some hyperlink to my items category in codeigniter.
$this->data['itemdata'] = array(
array(
'title' => 'Printers / Accessories',
'items' => ['Printers', 'Printer Cartridges', 'Compatible Toners'],
'brands' => ['hp', 'cannon', 'brother', 'toshiba', 'sharp']
),
how can I create it?
Updated
view file
<div class="items">
<ul class="floated">
<?php foreach ($item['items'] as $key => $value): ?>
<li><?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
</div>
You have to do it something like below:-
<li><?php echo $value;?></li>
Note:- I hope through URL you want to send user to some fruitful link. So change controller/function/uri to corresponding values.
Reference:-CodeIgniter - Correct way to link to another page in a view
Note:- if you want to remove link then do like below:-
<li><?php echo $value;?></li>
i have problem that i googled allot to try and figure out, but all solutions are variations on mine.
So i have output like this
<div class="row">
<?php $cat= '';?>
<div class="blank">
#foreach($posts as $post)
#if($cat!= $post->cat_id)
</div><div class="col-sm-3">
<p class="alert alert-info"><strong>{{$post->category_name}}</strong></p>
<?php $cat= $post->cat_id; ?>
#endif
</ul><ul>
<li>
{{$post->title}}
</li>
#endforeach
So basically i wont output that category name is in and then all the posts of that category within that div in ul li, and then close the DIV.
But i managed to make it only with this blank div, and closing ul and div before open, but that gives me invalid html, but its sorted good.
Is there any smart way to get this done?
Thanks
here is a working example. I think the problem was the place where you were opening and closing the foreach.
...
(I replaced the blade statements for plain php for clarity, but you should be able to change it back.)
EDIT:
I was not that far..
<?php $posts = [
['cat_id' => 1, 'cat_name' => 'a name', 'title' => 'title'],
['cat_id' => 1, 'cat_name' => 'a name2', 'title' => 'title2'],
['cat_id' => 2, 'cat_name' => 'another name', 'title' => 'title3'],
['cat_id' => 2, 'cat_name' => 'another name2', 'title' => 'title4'],
]; ?>
<div class="col-sm-3">
<?php $cat= '';?>
<?php foreach($posts as $post): ?>
<?php if($post['cat_id'] != $cat): ?>
<p class="alert alert-info">
<strong><?php echo $post['cat_name'];?></strong>
</p>
<ul>
<?php endif; ?>
<li> <?=$post['cat_name'];?> </li>
<?php if($post['cat_id'] == $cat): ?>
</ul>
<?php endif; ?>
<?php $cat= $post['cat_id']; ?>
<?php endforeach; ?>
</div>
Here I edited my previous answer, a few recommendations tho:
The point is not to just write code that works, but also maintainable and readable. That will help you or whoever has to change some functionality in the future.
Try to be as clear as you can be when asking, and provide an example of your desired output if needed (just like in the comment).
You could probably format the data before passing it to the view, so you can print it easily, for example, transforming the array I used in the above code to something like:
$posts = [
['cat_id' => 1, 'cat_name' => 'a name', 'posts' => [
['title' => 'a title','content' => 'whatever'],
['title' => 'another title','content' => 'whatever2'],
]
];
That way it would be waaay easier to show it, and it'll give you ways to
write clearer code.
Best regards!
So after extensive trying, i got what i wanted. Hope this is correct way of doing it.
<?php
$cat= '';
foreach($posts as $post){
if($cat != $post['cat_id']){
echo $cat!= '' ? '</ul></div>' : '';
echo '<div class="col-sm-4 col-md-3">
<p class="alert alert-info"><strong>'.$post['cat_name'].'</strong></p>
<ul>';
$cat= $post['cat_id'];
}
echo '<li>'.$post['title'].'</li>';
}
echo '</ul>'; //close last opened ul
echo '</div>'; //close last opened div
?>
I'm relatively new to php and I've been trying all day long to get this to work. I have a multiple array and want to echo each one in a specific format, and in groups.
So i've gone through stackoverflow and found this help:
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<div class="film"> <?php echo $curta[0]['titulo']; ?></div>
<div class="film"> <?php echo $curta[1]['titulo']; ?></div>
<div class="film"> <?php echo $curta[2]['titulo']; ?></div>
<div class="film"> <?php echo $curta[3]['titulo']; ?></div>
<div class="film"> <?php echo $curta[4]['titulo']; ?></div>
<div class="film"> <?php echo $curta[5]['titulo']; ?></div>
</li>
<? }; ?>
And this returns what I want but the last items of the array doesnt fill up to 6 and creates 2 extras empty divs and messes up the design.
This is a single example of the array i have:
<?php
$projetos = array (
"ugm" => array (
"id" => "ugm",
"titulo" => "Una Guerra Más",
"video" => "imagem",
"videoid" => "",
"height" => "$video_height_wide",
"sinopse" => "Um soldado moribundo deseja enviar sua última carta. Curta indisponível por exibição em festivais. Feito em parceria com a Universidad del Cine e LightBox Studios.",
"elenco" => "Ignacio J. Durruty - Rodrigo Soler - Ulisses Levanavicius - Aron Matschulat Aguiar",
"idioma" => "Inglês - Português",
"camera" => "Sony EX1",
"formato" => "HD",
"duracao" => "9'55''",
"ano" => "2012",
"tipo" => "Curta",
"credito" => "Direção - Edição - Produção - Roteiro",
), (...)
I want to be able to edit just one div that will be the master for the others... and using the implode I've read on another question but didn't worked to echo the strings I wanted..
Would please someone help out?
thanks in advance!
<?php foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<?php foreach($curta as $detail) { ?>
<div class="film"> <?php echo $detail['titulo']; ?></div>
<?php } ?>
</li>
<? }; ?>
Why not use a loop to iterate over $curta?
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<? foreach($curta as $c) { ?>
<div class="film"><? echo $c['titulo']; ?></div>
<? } ?>
</li>
<? }; ?>
but the last items of the array doesnt fill up to 6
As this is going to happen most of the time, you can't assume that every chunk has 6 elements, so you'll have to iterate over the chunk:
<? foreach(array_chunk($projetos, 6) as $curta ) { ?>
<li style='display:block'>
<? foreach($curta as $c) { ?>
<div class="film"> <?php echo $c['ugm']['titulo']; ?></div>
<? }; ?>
</li>
<? }; ?>
This way you are sure to display no empty divs.
This lines:
<div class="film"> <?php echo $curta[0]['titulo']; ?></div>
should be like this:
<div class="film"> <?php echo $curta[0]['ugm']['titulo']; ?></div>
that should do what you want.