I’m fairly new to php and struggling with what I think is a basic but just can’t get my head round how to do it.
How do I use 2 foreach statements within each other?
For example I need a header on a page which shows a users job title and then a list below of the users. I have 1 array with job titles and another with names, but cannot get it to output one job title into the header followed by a list of names, then another job title into the next header followed by a list of corresponding names, etc etc.
Basically, sort the results like:
manager | bob
manager | bill
janitor | jane
janitor | joe
Where the first field is relation, and the second name.
Grab a piece of paper, and run through what I posted, writing out what should be output - and tracking that $relation variable.
You can see by the syntax highlighting why you get that error, you are closing the php tags in the middle of a foreach loop, and php doesn’t get the } it needs.
Instead of what you have, you can sort the query by relation (and name if you want) and do this
$relation = '';
while($row = mysql_fetch_array($result)) {
if($relation != $row['relation']) { // in order so we found a new relation
echo '<h1>'.$row['relation'].'<h1>';
$relation = $row['relation']; // store current relation
}
echo $row['name'];
}
it should actually be done wioth just one query, a join query with an appropriate ORDER BY clause, and then you need only one loop in your php, but with current/previous checking so that you can break out new titles
Cheers, that kind of worked, but was calling all names through to each user type.
my code is
<?php
include $_SERVER['DOCUMENT_ROOT'] . '\\360feedback\\includes\\db.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '\\360feedback\\includes\\helpers.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '\\360feedback\\includes\\magicquotes.php';
$result = mysqli_query($link, 'SELECT * FROM user ');
if (mysqli_num_rows($result) <= 0)
{
$output = "No Results Returned";
include $_SERVER['DOCUMENT_ROOT'] . '\\360feedback\\includes\\output.html.php';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$user[] = $row['firstname'];
$relation[] = $row['relation'];
}
?>
<p>
<p>These are users with relation
<?php foreach($relation as $relations)
{
echo $relations . "</p>"; ?>
foreach($user as $users)
{
echo $users "<br />";
}} ?>
I’ve iserted the HTML tags to try and split it out a bit but get the error message
Parse error: syntax error, unexpected $end in D:\Documents\AI24\Web\360feedback\showusers.php on line 36
I’m stumped by this and yet it seems such a simple task