Multi-dimensional PHP array of values not displaying correctly

ari1989 :

I have a multidimensional array of fruits below.

$fruits = [
    'ORANGE' =>
        [
            'Size' => '0.20',
            'Cost' => '0.49',
            'Lbs.' => '0.60',
    ]
    'LEMON' =>
        [
            'Size' => '0.15',
            'Cost' => '0.29',
            'Lbs.' => '0.20',
    ]
];

I want to display the fruit array like below, but it is not working as expected.

-----| ORANGE | LEMON |
Size |   0.20 |  0.15 |
Cost |   0.49 |  0.29 |
Lbs. |   0.60 |  0.20 |

My code below is not quite doing what I expected. Any suggestions? Thank you!

echo '<table id="fruits" style="width:400px;border:1px solid black;">' . PHP_EOL;
echo '<tbody>' . PHP_EOL;

foreach ($fruits as $fruitkey => $fruitvalue) {
    echo '<th>' . $fruitkey . '</th>';

    foreach ($fruitvalue as $key => $value) {
        echo '<tr>' . PHP_EOL;

        echo '<td>' . PHP_EOL;
        echo $key . PHP_EOL;
        echo '</td>' . PHP_EOL;

        echo '<td>' . PHP_EOL;;
        echo number_format($value, 2) . PHP_EOL;
        echo '</td>' . PHP_EOL;

        echo '</tr>' . PHP_EOL;
    }
}
echo '</tbody>' . PHP_EOL;
echo '</table">' . PHP_EOL;
Ajith :

Can you try the below code

<?php

$fruits = [
    'ORANGE' =>
        [
            'Size' => '0.20',
            'Cost' => '0.49',
            'Lbs.' => '0.60',
    ],
    'LEMON' =>
        [
            'Size' => '0.15',
            'Cost' => '0.29',
            'Lbs.' => '0.20',
    ]
];
$keys = array_keys($fruits);
if(!empty($keys))
    $innerKeys = array_keys($fruits[$keys[0]]);

echo '<table id="fruits" style="width:400px;border:1px solid black;">';
echo '<thead><tr>';
echo '<td>----</td>';
foreach($keys as $key)
    echo '<td>'.$key.'</td>';
echo '</tr></thead>';
echo '<tbody>';
foreach($innerKeys as $inKey){
    echo '<tr>';
    echo '<td>'.$inKey.'</td>'; 
    foreach($fruits as $fKey => $val){
        echo '<td>'.$val[$inKey].'</td>';       
    }
    echo '</tr>';
}
echo '</tbody>';
echo '</table>';

Demo Link

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related