DivFellaPoor
DivFellaPoor

Reputation: 43

How can I create a table from a Multidimensional Array using Array Values to define table rows?

I have an array in PHP that looks like this... it's sorted in ascending order by the 'generation' value

Array
(
    [0] => Array
        (
            [userID] => 1
            [userName] => Grandfather
            [generation] => 1
        )

    [1] => Array
        (
            [userID] => 2
            [userName] => Father
            [generation] => 2
        )

    [2] => Array
        (
            [userID] => 3
            [userName] => Son
            [generation] => 3
        )

    [3] => Array
        (
            [userID] => 4
            [userName] => Daughter
            [generation] => 3
        )

)

I want to create an HTML table that looks like this...

enter image description here

One row for each generation, with each member of the generation seperated by a comma.

I've tried multiple versions of 'foreach' and 'while' solutions but haven't been able to get it right.

This is the closest I have come to success...

    echo '<table>';
    $x = 1;
    foreach ($usersArray as $subArray){
        if($subArray['generation'] == $x){
            echo '<tr>';
            echo '<td>'.$subArray['userName'].'</td>';
            echo '</tr>';
        }
        $x++;
    }
    echo '</table>';

This code however will only print the first member of each generation giving a table of...

enter image description here

Any help is appreciated.

Upvotes: 0

Views: 69

Answers (1)

Progrock
Progrock

Reputation: 7485

You could create a new array grouped by generation. And then loop through that and implode each value for row data.

<?php

$items = 
[
    [

        'name' => 'Grandfather',
        'gen'  => 1
    ],
    [
        'name' => 'Father',
        'gen'  => 2
    ],
    [
        'name' => 'Son',
        'gen'  => 3
    ],
    [
        'name' => 'Daughter',
        'gen'  => 3
    ]
];

foreach ($items as $item) {
    $gens[$item['gen']][] = $item['name'];
}

var_export($gens);

print_r(
    array_map(
        function($item) {
            return implode(', ', $item);
        }, 
        $gens
    )
);

Output:

array (
  1 => 
  array (
    0 => 'Grandfather',
  ),
  2 => 
  array (
    0 => 'Father',
  ),
  3 => 
  array (
    0 => 'Son',
    1 => 'Daughter',
  ),
)Array
(
    [1] => Grandfather
    [2] => Father
    [3] => Son, Daughter
)

You could skip the array_map above and just loop and implode, here's an example of spitting out rows:

foreach($gens as $gen) {
    echo '<tr><td>', implode(', ', $gen), '</td></tr>';
};

Upvotes: 1

Related Questions