Romain
Romain

Reputation: 85

SQL + PHP Display multidimensional array

My SQL Querie returns those values :

Column1     Column2
V1          V1
V1          V2
V1          V3
V1          V4
V2          V1
V2          V2
V3          V1

Fetchall() stores result in a Array like that.

Array
(
    [0] => Array
        (
            [Column1] => V1         
            [Column2] => V1
        )

    [1] => Array
        (
            [Column1] => V1         
            [Column2] => V2
        )

    [2] => Array
        (
            [Column1] => V1         
            [Column2] => V3
        )

    [3] => Array
        (
            [Column1] => V1         
            [Column2] => V4
        )
    [4] => Array
        (
            [Column1] => V2
            [Column2] => V1
        )
    [5] => Array
        (
            [Column1] => V2
            [Column2] => V2
        )
    [6] => Array
        (
            [Column1] => V3
            [Column2] => V1
        )
)

I would like to display like that. I try with double foreach ...

V1
    V1
    V2
    V3
    V4
V2
    V1
    V2
V3
    V1

Upvotes: 1

Views: 34

Answers (2)

Minwork
Minwork

Reputation: 1022

From what I see you want to group results by Column1 value. In that case you can simply write:

$result = [];

foreach ($array as $row) {
    // Using PHP 7.1+
    ['Column1' => $key, 'Column2' => $value] = $row;
    // Using PHP before 7.1
    $key = $row['Column1'];
    $value = $row['Column2'];

    if (! array_key_exists($key, $result)) {
        $result[$key] = [$value];
    } else {
        $result[$key][] = $value;
    }
}

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94662

A simple foreach loop should do this quite happily. All you have to remember the value of Column1 so you can tell when the primary key for want of a better word has changed.

I tested this on the CLI so you may have to amend it to use some HTML if you want it to show nicely ona browser.

$arr = [
        ['Column1'=>'V3' , 'Column2'=>'V1'],
        ['Column1'=>'V1' , 'Column2'=>'V1'],
        ['Column1'=>'V2' , 'Column2'=>'V1'],
        ['Column1'=>'V1' , 'Column2'=>'V2'],
        ['Column1'=>'V1' , 'Column2'=>'V3'],
        ['Column1'=>'V1' , 'Column2'=>'V4'],
        ['Column1'=>'V2' , 'Column2'=>'V2'],
];

$col1 = array_column($arr, 'Column1');
$col2 = array_column($arr, 'Column2');

array_multisort($col1, SORT_ASC, $col2, SORT_ASC, $arr);

$lastKey = null;
foreach($arr as $subarr) {
    if ( $lastKey != $subarr['Column1'] ) {
        echo $subarr['Column1'] . PHP_EOL;
        echo "\t" . $subarr['Column2'] . PHP_EOL;
        $lastKey = $subarr['Column1'];
    } else {
        echo "\t" . $subarr['Column2'] . PHP_EOL;
    }
}

RESULT

V1
        V1
        V2
        V3
        V4
V2
        V1
        V2
V3
        V1

Upvotes: 1

Related Questions