开发者

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 pa开发者_开发问答ge.

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
    OUTPUTS :
    file01, FBX
    file02, JPG
    file03, JPG
ID : 2
    OUTPUTS :
    file05, FBX
    file06, JPG
    file07, JPG
ID : 3
    OUTPUTS :
    file010, FBX
    file011, JPG

... etc

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


<?php 
$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.

<?php

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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜