I have sent $data['items'] to my view which has created an array full of objects which I can echo with a foreach loop.
foreach($items as $row)
{
echo $row->NAME . " - " . $row->COLOUR . "<br>";
}
what I want to do is echo them to the browser in groups with the name of the colour as a header tag then start the loop for that colour. I'm just not sure what type of loop to do or should I have a loop within a loop?
BLUE
-item 1
-item 3
RED
-item 2
-item 4
-item 5
$list = array();
foreach($items as $row)
{
$list[$row->COLOUR][] = $row->NAME;
}
$header = null;
foreach($list as $item)
{
if($header != $item->COLOUR)
{
echo '<h3>' . $item->COLOUR . '</h3>';
$header = $item->COLOUR;
}
echo '- ' . $item->NAME . '<br />';
}
You probably want an interim two-dimensional array:
$tmp = array();
foreach($items as $row)
{
// this code groups all items by color
$name = $row->NAME;
if( !isset ($tmp[ $name ] ) ) $tmp[ $name ] = array();
$tmp[ $name ][] = $row->COLOUR;
}
foreach( $tmp as $color => $items )
{
// colors are now keys to the temp array
echo $color;
// these are all of the items grouped under the current color
foreach( $items as $item )
{
// output the item.
echo "<br /> - $item";
}
echo "<br />";
}
Related
How can I generate header for printed 2d array in php?
So my array look like this:
$tab=array(
array(0,1,2,3),
array(1,2,3,4),
array(2,3,4,5)
)
This code:
foreach ($tab as $key => $row){
echo '<b>o<sub>'.($key+1).'</sub></b> ';
foreach ($row as $item) {
echo $item.' ';
}
echo '<br>';
}
Print this:
o1 0 1 2 3
o2 1 2 3 4
o3 2 3 4 5
But I need this:
a1 a2 a3 d
o1 0 1 2 3
o2 1 2 3 4
o3 2 3 4 5
Where lenght of rows may be diferent and last column always must be d
Thanks for help
You can check if this is the first iteration in the first foreach and if so, add the first line.
foreach ($tab as $key => $row) {
// If first iteration, add the header
if ($key === 0)
{
foreach ($row as $i => $item)
{
// Last header must be 'd'
if ($i === count($row) - 1)
echo '<b>d</b>';
else
echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
}
echo '<br />';
}
// Add the current row
echo '<b>o<sub>' . ($key + 1) . '</sub></b> ';
foreach ($row as $item) {
echo $item . ' ';
}
echo '<br />';
}
If the first row is a static row, then you can simply print it using echo function at first.
But if its a dynamic tab as well, then you can use the following code:
$count = count($tab[0]);
for($i = 1; $i <= $count; $i++)
{
if($i != $count) echo '<b>a<sub>' . ($i + 1) . '</sub></b> ';
else echo '<b>d</b> ';
}
foreach ($tab as $key => $row){
echo '<b>o<sub>'.($key+1).'</sub></b> ';
foreach ($row as $item) {
echo $item.' ';
}
echo '<br>';
}
You can try this, except use <table> or <div> to align your elements.
foreach ($tab[0] as $key => $item)
echo $key === 0 ? title(' ', ' ') : title('a', $key);
echo title('d', '') . '<br>';
function title(string $letter, string $index)
{
return "<b>{$letter}<sub>{$index}</sub></b>";
}
I have 2 arrays: post_titles and posts. How do I print them one after another with foreach?
When I use 1 array, it works fine:
<?php foreach ($titles as $row) { ?>
<?php echo $row['post_title'] ?> <br>
<?php } ?>
I want data to be printed like this:
Title
Post
<br>
Title
Post
<br>
etc.
If each item in the titles and post correspond to each other (eg titles[1] and posts[1], titles[2] and posts[2]), you could use a for loop.
eg.
for($i = 0; $i < count($titles); $i++) {
echo $titles[$i];
echo $posts[$i];
echo "<br>";
}
or
foreach ($titles as $i => $value ){
echo $value ." <br>" . $posts[$i] . " <br>";
}
If the array have the same index key you can use this
<?php
foreach($titles as $key=> $value) {
echo $value . ' - ' $post[$key] . '<br>';
}
?>
If the 2 arrays are in sync i.e. the same length and arr1(0) equates to arr2(0) then its easy
<?php
foreach ($post_titles as $i => $title) {
echo $title . '<br>' . $posts[$i] . '<br>';
}
?>
I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}
I've got a rather complicated set of loops that pulls data out of mysql and compares it to values in an array and increments a counter. When I echo a flag when the counter is incremented, I get a bijilion flags (there're like 2600 records returned from the mysql query). But each time it prints, the counters are always 1 and when I print the counter's value at the end, it shows up as zero. It seems like something is re-setting the counter…
code
# ARRAY
$demographics=array(
"region"=>array(
"Northeast"=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
"West"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"societal envirn"=>array(
"Urban"=>array('total'=>0,'consented'=>0,'completed'=>0)
),"age"=>array(
'18-19'=>array('total'=>0,'consented'=>0,'completed'=>0),
'20-24'=>array('total'=>0,'consented'=>0,'completed'=>0),
//more...
'55-59'=>array('total'=>0,'consented'=>0,'completed'=>0)
),
//more...
);
# LOOPS
while ($dbrecord = mysql_fetch_assoc($surveydata)) {
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic=>$options ) {
foreach ( $options as $option=>&$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
}
} // if age
else if ($option===$dbcellval){
$counter['total']++;
echo '$' . $option . "['total'] = " . $counter['total'] . "<br />";
if ($dbrecord['consent']==="1"){
$counter['consented']++;
echo '$' . $option . "['consented'] = " . $counter['consented'] . "<br />";
if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
echo '$' . $option . "['completed'] = " . $counter['completed'] . "<br />";
break 3;
} // if
} // if
break 2;
} // else if $option==$dbcellval
} // foreach $options
} // foreach $demographics
} // foreach $dbrecord
} // while
sample output
$40-44['total'] = 1
$White['total'] = 1
$35-39['total'] = 1
$Northeast['total'] = 1 // the 'total' counter is 1
$Northeast['consented'] = 1
$Northeast['completed'] = 1
$South['total'] = 1
$Northeast['total'] = 1 // notice the 'total' counter is 1 again :(
$Northeast['consented'] = 1
$Northeast['completed'] = 1
You're defining counter from a foreach instruction, as $value in foreach($foo as $key=>$value), when using the foreach you only have a local copy of $counter.
You need to use either foreach($foo as $key=>&$value) or to refer to the full array path of your counter from $demographics.
You need to reference your array at each level, otherwise you are working on a copy of the data:
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic => &$options ) {
foreach ( $options as $option => &$counter ) {
if($demographic==="age"){
list($min,$max) = explode('-', $option);
if ($dbcellval >= $min && $dbcellval <= $max){
$counter['total']++;
What if you simply stick with the $demographics variable.
i.e.
...
foreach ( $options as $option ) {
...
$demographics[$option]['total']++;
...
I'm able to display id and tags in the foreach loop no problem. But I'm having trouble showing title and height. I'm not sure how to call them into the foreach loop.
I can call them in the while loop so I know that they are working.
$persons = array();
$tags = array();
while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
if(!isset( $persons[$row['id']]))
{
$persons[$row['id']]['title'] = $row['title'];
$persons[$row['id']]['height'] = $row['height'];
$persons[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach( $persons as $pid => $p)
{
echo 'id: # ' . $p['id'] ;
echo 'title: ' . $p['title'];
echo 'height: ' . $p['height'];
echo '' . implode( ', ', $tags[ $p['id'] ]) . '';
echo '<br /><br />';
}
You're overwriting $persons[ $row['id'] ] when you set the tags, so you lost the other data.