Patrioticcow
Patrioticcow

Reputation: 27038

How to create table from array?

I have a bit of difficulty creating some tables in a specific order from this array: $test.

The array looks like this:

Array
(
    [ET5] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 430
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 406
            )
        )
    )
    [FA] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 0
            )
        )                   
        [1] => Array(
            [0] => Array(
                [total] => 0
            )
        )
    )
    [ET5] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 189
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 228
            )
        )
    )
    [FA] => Array(
        [0] => Array(
            [0] => Array(
                [total] => 0
            )
        )
        [1] => Array(
            [0] => Array(
                [total] => 0
            )
        )
    )
)

and the tables I want to create should look like this:

table1

test1      test2   test3
ET5        430     189
FA         0       0

table2

test1      test2    test3
ET5        406      228
FA         0        0

test1, test2, test3 are known strings

I'm a bit stuck on this one, notice how the values from the ET5 are in two tables.

Any ideas on this one?

Upvotes: 0

Views: 1292

Answers (1)

Kai Qing
Kai Qing

Reputation: 18833

You should definitely not overwrite the keys of the array like you do above.

I would separate what you want in each tables by adding them as arrays to your already multi-dimensional array...

$test = array(
    [0] => array(
        [ET5] => array(), //rest of inner contents inside these arrays of course
        [FA] => array()
    ),
    [1] => array(
        [ET5] => array(),
        [FA] => array()
    )
);

then run your foreach loop as you would on any array:

<?php foreach($test AS $key => $val): ?>
<table>
    <tr>
        <th>Test1</th>
        <th>Test2</th>
        <th>Test3</th>
    </tr>
    <?php foreach($val AS $v => $info): ?>
    <tr>
        <td><?php echo $v; ?></td>
        <td><?php echo $info[0][0]['total']; ?></td>
        <td><?php echo $info[1][0]['total']; ?></td>
    </tr>
    <?php endforeach; ?>
</table>    
<?php endforeach; ?>

Upvotes: 1

Related Questions