multidimensional array - PHP neat way of displaying results of a JOIN statement with duplicate IDs


I have a multidimensional array which is the result of a JOIN statement. And I was wondering what would be a neat way of displaying this on the page.

Because of the JOIN, many of the rows have duplicate IDs, and while displaying it on the page, I wish to display the ID only once (even if there may be duplicates of this id later on in the array) , followed by the non-unique columns of the row

I guess I am not making myself clear so, here is an example result from the JOIN :

$job_rows = array(
                    array("id" => 1, "output" => "file01", "output_type" => "FBX"),
                    array("id" => 1, "output" => "file02", "output_type" => "JPG"),
                    array("id" => 1, "output" => "file03", "output_type" => "JPG"),
                    array("id" => 2, "output" => "file05", "output_type" => "FBX"),
                    array("id" => 2, "output" => "file06", "output_type" => "JPG"),
                    array("id" => 2, "output" => "file07", "output_type" => "JPG"),
                    array("id" => 3, "output" => "file010", "output_type" => "FBX"),
                    array("id" => 3, "output" => "file011", "output_type" => "JPG")

I would like to display it like this :

ID : 1
    file01, FBX
    file02, JPG
    file03, JPG
ID : 2
    file05, FBX
    file06, JPG
    file07, JPG
ID : 3
    file010, FBX
    file011, JPG

... etc

basically combining the common IDs during echo'ing the results on page. Thanks




$output = array();
foreach ($job_rows as $key => $value)
    $output[$value['id']][] = $value['output'] . ", " . $value['output_type'];

Will get you pretty close. Then, after you have the output array formatted nicely, you can loop through that.


foreach ($output as $id => $data)
    echo $id . "\n";
    foreach ($data as $k => $v)
        echo "\t $v\n";



If you will have your IDs in order as your question suggests, then you can keep track of the current ID and only output a new one if the id has changed. Something like

$curId = -1;
foreach($job_rows as $row) {
    if($row['id'] != $curId) {
        echo 'ID: '.$row['id']."\n\tOUTPUTS : \n";
        $curId = $row['id'];
    echo "\t".$row['output'].', '.$row['output_type']."\n";

People are also looking for solutions to the problem: php mobile website, need advice


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.