简体   繁体   English

多维 PHP 值数组未正确显示

[英]Multi-dimensional PHP array of values not displaying correctly

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;

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演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM