PHP Foreach with two or more arrays - php

How to use Foreach on two or more php arrays?
My arrays are $boardType, $hotelPrice and $hotelName
Solution is to add $index in the other arrays as suffix
<?php foreach ($hotelName as $index => $name):?>
<div>
<p><?php echo $name;?></p>
<p><?php echo $hotelPrice[$index];?></p>
<p><?php echo $boardType[$index];?></p>
</div>
<?php endforeach?>

This should work for you:
(Here I just go through all 3 arrays with array_map() an print them in the structure you want)
<?php
array_map(function($v1, $v2, $v3){
echo "<div>";
echo "<p>$v1</p>";
echo "<p>$v2</p>";
echo "<p>$v3</p>";
echo "</div>";
}, $boardType, $hotelPrice, $hotelName);
?>
Example input/output:
$boardType = [1,2,3];
$hotelPrice = [4,5,6];
$hotelName = [7,8,9];
<div>
<p>1</p>
<p>4</p>
<p>7</p>
</div>
<div>
<p>2</p>
<p>5</p>
<p>8</p>
</div>
<div>
<p>3</p>
<p>6</p>
<p>9</p>
</div>

If all arrays have exactly the same size you could use each to iterate through the other arrays at the same time as $hotelName:
<?php foreach ($hotelName as $index => $name):?>
$price = each($hotelPrice);
$boardType = each($boardType);
<div>
<p><?php echo $name;?></p>
</div>
<?php endforeach?>
However, in that case it would probably being better to have just a single array containing all the data.

Related

Add comma between foreach looped items but not at end

I'd like to achieve on adding a comma between my authors in my foreach but each time I make any references, it adds a comma at the end also.
Here is what I have below:
<div class="four-sixths first">
<img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/>
<h2 class="mb-5"><?= $recipe->get_title() ?></h2>
<span><?= $recipe->get_date() ?></span> -
<?php foreach ($recipe->get_authors() as $profile): ?>
<?= $profile->get_name() ?>,
<?php endforeach; ?>
<p><?= $recipe->get_content() ?></p>
</div>
Which gives me the following results:
How can I prevent a comma at the end?
Since you were skeptical about implode, here's a simple example (just showing the loop):
<?php foreach ($recipe->get_authors() as $profile):
$links[] = '' . $profile->get_name() . '';
endforeach; ?>
<?= implode(', ', $links); ?>
An alternative using join:
<div class="four-sixths first">
<img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/>
<h2 class="mb-5"><?= $recipe->get_title() ?></h2>
<span><?= $recipe->get_date() ?></span> - <?= join(", ", array_map(function ($profile) { return sprintf('%s', $profile->get_url(), $profile->get_name()); }, $recipe->get_authors())) ?>
<p><?= $recipe->get_content() ?></p>
</div>
Wasn't able to test it but basically store results to $authors first, and in this way you can count it without recalling the method get_authors. While $cnt keeps track base 1 and can be compared directly on the length.
<?php
$authors = $recipe->get_authors();
$cnt = 0;
?>
<div class="four-sixths first">
<img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/>
<h2 class="mb-5"><?= $recipe->get_title() ?></h2>
<span><?= $recipe->get_date() ?></span> -
<?php foreach ($authors as $profile) { $cnt++; ?>
<?= $profile->get_name() ?><?php
if ($cnt < count($authors)) echo ",";
?>
<?php } ?>
<p><?= $recipe->get_content() ?></p>
</div>

Print the specific values from the array

I get the result from my database i this type of array format.Now i want to print the question,answer and category name from the array what I do?
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data->title;?>">
I tried these cod but not get the answer.In $var i get the all the array value
Things to consider:-
1.Your sub-array is again an array so you need to use foreach() on sub-array too. (So basically two foreach())
2.You need to close divs as well as foreach() loops too.
So code need to be like below:-
<?php
foreach($var as $data){
foreach($data['data'] as $dat){
?>
<div class="faqHeader"> <?php echo $dat['category_name'];?>
<div class="panel-group" id="<?php echo $dat['questions'];?>"><?php echo $dat['questions'];?></div>
<div class="panel-group" id="<?php echo $dat['answer'];?>"><?php echo $dat['answer'];?></div>
</div>
<?php } }?>
you can use two loops to simplify your task:-
foreach($var as $index=>data){
echo $data['name']; // this will be your category name
foreach($data as $questionIndex=>$questionData){
echo $questionData['question'];
echo $questionData['answer'];
}
}
Since your array contains multiple data and data contains multiple values itself, you need two foreaches here:
foreach($var as $item) {
foreach($item['data'] as $info) {
var_dump($info);
}
}
Please try this code
<?php
$v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['data'][0]['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data['name'];?>">
<?php
}
?>
You don't have any 'title' index in your array so you may change it to 'name'

string is not getting exploded

Here is my code where explode function is not getting correctly.code looks like this
<div id="demo-1" data-zs-src='[<?php foreach( $slides as $slide ){?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>"<?php }?>]' data-zs-overlay="dots">
<div class="demo-inner-content">
<h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>
my result looks like this
<div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif""http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg""http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"]' data-zs-overlay="dots">
<div class="demo-inner-content">
<h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>
</div>
i want to get comma in between the result that means my result should be like this
<div id="demo-1" data-zs-src='["http://localhost/fahiz_kitchen/uploads/upload-file1496902770.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901910.gif",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901900.jpg",
"http://localhost/fahiz_kitchen/uploads/upload-file1496901887.jpg"
plz use this;
<?php foreach( $slides as $slide ){
$images= base_url()."uploads/". $slide->image;
var_dump($images);
$arr= explode(',',$images);
print_r($arr);
}
?>
Chnage it like.
$data = [<?php
foreach( $slides as $slide ){
?>"<?php echo base_url();?>uploads/<?php echo $slide->image;?>",
<?php }?>];
$finaldata = rtrim($data, ',');
<div id="demo-1" data-zs-src="'.$finaldata.'" data-zs-overlay="dots">
<div class="demo-inner-content">
<h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>
You are starting php inside already started it.
After doing some changes i got the result and the code used for that is as follows
<?php foreach ( $slides as $slide ) {
$data[] = $images='"'.base_url()."uploads/". $slide->image.'"';
$y=implode(',',$data);
}?>
<div id="demo-1" data-zs-src='[<?php echo $y;?>]' data-zs-overlay="dots">
<div class="demo-inner-content">
<h1><span>Tasty</span> & <span>Healthy</span></h1>
<p>For those who have taste for life.</p>
</div>

How can I divide/split an array?

I have an array here which has (30 values e.g.).And I displayed it on a div. I want to split them into 3parts and display them in a three separated div. How can I do this one?Here's my code:
<div class="span4">
<?php if($col):?>
<?php foreach($col as $names):?>
<label class="checkbox">
<input type="checkbox" id="chk_distinct" class="check"
value="<?php echo $names->COLUMN_NAME;?>">
<?php echo $names->COLUMN_NAME;?></label>
<?php endforeach;?>
<?php endif;?>
</div>
It will display this one:
<div>
Checkbox1
Checkbox2
Checkbox3
Checkbox4
...
Checkbox30
</div>
I wanted it to look like this one:
<div1> <div2> <div3>
Checkbox1 Checkbox11 Checkbox21
Checkbox2 Checkbox12 Checkbox22
Checkbox3 Checkbox13 Checkbox23
Checkbox4 Checkbox14 Checkbox24
Checkbox5 Checkbox15 Checkbox25
... ... ...
Checkbox10 Checkbox20 Checkbox30
</div> </div> </div>
Any Idea about this one?Beginner here..
Use array_chunk For example
$cols = array_chunk($col, 10, true);
foreach ($cols as $col)
{
echo '<div>';
foreach ($col as $names)
{
echo '<label>'.$names->COLUMN_NAME.'</label>';
}
echo '</div>';
}

On every third iteration in PHP

I would like to output some specific HTML on the third iteration of a loop in PHP. Here is my code:
<?php foreach ($imgArray as $row): ?>
<div class="img_grid"><?= $row ?></div>
<?php endforeach; ?>
On the third iteration of this loop, Instead of displaying:
<div class="img_grid"><?= $row ?></div>
I would like to display:
<div class="img_grid_3"><?= $row ?></div>
I would like to end up with this if my array looped 8 times:
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid_3">[some html]</div>
<div class="img_grid">[some html]</div>
<div class="img_grid">[some html]</div>
Thanks
Assuming $imgArray is an array and not an associative array (i.e. it has numeric indices), this is what you want:
<?php foreach($imgArray as $idx => $row): ?>
<?php if($idx % 3 == 2): ?>
<div class="img_grid_3"><?php echo $row; ?></div>
<?php else: ?>
<div class="img_grid"><?php echo $row; ?></div>
<?php endif; ?>
<?php endforeach; ?>
You could tighten it up a bit like this:
<?php foreach($imgArray as $idx => $row):
if($idx % 3 == 2) {
$css_class = 'img_grid_3';
} else {
$css_class = 'img_grid';
}
?>
<div class="<?php echo $css_class; ?>"><?php echo $row; ?></div>
<?php endforeach; ?>
Or even more (some folks would just go with a ternary conditional inline in the HTML), but the law of diminishing returns kicks in eventually with regard to readability. Hopefully this gives you the right idea, though.

Categories