I have a MySQL query which returns a set or rows to me,

PersonID | ClassID | ...

As I loop through each row, I'm echoing data into a table. So far it's 101.

The issue I now have is some PersonID's are duplicated (for good reason) but they are grouped together. Table structure change is not an option.

What I want to do is combine all my PersonID's which match together as I echo them. There will likely only be 1 row each, some have 2, 3 or more is possible but unlikely.

Any ideas how I could manipulate this in PHP?

I'm thinking saving all my current row into a variable. On the next row if it matches add to it, if not echo it and replace the variable the new current row?

Thoughts?

nzkiwi80

You probably want to index/pivot the data using the PersonID as the main array index when you fetch the data, then simply loop over the indexed data (key = PsersonID, value = array of corresponding rows of data) to produce the output.

pbismad Could you explain that with a very simple code example.

I was doing to set $pID = 0;

The inside my foreach result do something like

`if ($p !== $row['PersonID']){
// create variable as new person
} else{
// update same person
}

echo data`

But that won't work for the first row let alone all other rows

    // index/pivot the data using the PersonID as the main array index
    // if you are using the PDO extension, there's a fetch mode that does this for you
    $result = [];
    while($row = fetch statement for the database extension you are uisng)
    {
    	$result[$row['PersonID']][] = $row;
    }
    
    
    // produce the output
    foreach($result as $PersonID=>$rows)
    {
    	// output any heading using the $PersonID value
    	echo "Person ID: $PersonID<br>";
    	
    // loop over the rows of data for the current PersonID
    foreach($rows as $row)
    {
    	echo "Class ID: {$row['ClassID']}<br>";
    }
    }
    
    Write a Reply...