Welcome Guest, Not a member yet? Register   Sign In
display title about grouped result in foreach
#1

[eluser]ppwalks[/eluser]
Hi all,

I need a bit of assistance, I have a foreach loop iterating through an array which is grouped by a field called level, what I need to do is add a h2 tag above each set of grouped results can anyone help with this please.

Here is my sql

Code:
$sql = "SELECT `id`, `title`, `level` from `toplevels`  GROUP BY level, title ORDER BY id ASC";

and my array is as follows

Code:
Array ( [0] => Array ( [id] => 1 [title] => Why Sewell [level] => 1 ) [1] => Array ( [id] => 2 [title] => About Sewell [level] => 1 ) [2] => Array ( [id] => 3 [title] => Services [level] => 1 ) [3] => Array ( [id] => 4 [title] => Careers [level] => 1 ) [4] => Array ( [id] => 5 [title] => Giving Back [level] => 1 ) [5] => Array ( [id] => 7 [title] => Paul's about us page 6 [level] => 2 ) [6] => Array ( [id] => 8 [title] => Hi all, another url problem [level] => 2 ) [7] => Array ( [id] => 9 [title] => a test [level] => 2 ) [8] => Array ( [id] => 14 [title] => Kierans About us page [level] => 2 ) [9] => Array ( [id] => 15 [title] => Article 1b [level] => 3 ) )

I need all the data with level 1 in one group and with a header and so on for each level assigned.

Thanks in advance Paul
#2

[eluser]Aken[/eluser]
You should loop your results and filter them into a new array, using the level as an array key.

Code:
$sorted = array();

foreach ($result as $row)
{
$sorted[$row['level']][] = $row;
}

print_r($sorted);
#3

[eluser]ppwalks[/eluser]
Thanks but not what I was looking for any suggestions

Want to display

Code:
<h2>About Us</h2>
...... All levels 1 stuff
<h2>Some more stuff</h2>
......All level 2 stuff

And so on...

#4

[eluser]ppwalks[/eluser]
anyone this is driving me nuts
#5

[eluser]CroNiX[/eluser]
Code:
$last_title = '';  //keep track of the last title used

foreach($your_array as $data)
{
  //compare to see if the current title is the same as the last one, if NOT print it
  if ($data['title'] !== $last_title)  
  {
    echo '<h2>' . $data['title'] . '</h2>';
  }
  //print the rest of the data
  echo '<div>' . $data['more_stuff'] . '</div>';

  //now set $last_title so you can check against it during the next loop
  $last_title = $data['title'];  
}




Theme © iAndrew 2016 - Forum software by © MyBB