将二维数组打印为按列值排序的格式化 HTML 列表项

问题描述 投票:0回答:2

所以我的导师给了我这个,为了完成我有点卡住了。我已经厌倦了很多方法,但没有找到显示数据的正确方法。

使用说明:

/*
* Below is an array of cakes and information about them.
* Please write a script that generates the following html snippet
*
*    <ul>
*      <li>Wedding Cake<br />Flavour: hopes and dreams</li>
*       <li>Chocolate Gateau<br />Flavour: chocolate</li>
*       <li>Black Forest Gateau<br />Flavour: fruity</li>
*       <li>Victoria Sponge<br />Flavour: vanilla</li>
*       <li>Tottenham Cake<br />Flavour: strawberry</li>
*    </ul>
*
* (html or xhtml <br> / <br /> is fine!)
* Note that the list is ordered in descending order of price.
*/

输入数据:

$cakes = array(
    "chocolate_gateau" => array(
        "flavour" => "chocolate",
        "price" => 3.50
    ),
    "victoria_sponge" => array(
        "flavour" => "vanilla",
        "price" => 1.50
    ),
    "black_forest_gateau" => array(
        "flavour" => "fruity",
        "price" => 2.20),
    "tottenham_cake" => array(
        "flavour" => "strawberry",
        "price" => 0.58
    ),
    "wedding_cake" => array(
        "flavour" => "hopes and dreams",
        "price" => 5.23
    )
);

我的代码:

function cakeList($cakes) {
    echo "<ul>";
        foreach($cakes as $value) {
            if (is_array($value))
                cakeList($value);
            else
                echo '<li>' . $value . '</li>';
            }
            echo "</ul>";
        }
        echo cakeList($cakes);

他们希望我在 html 中生成一个列表,以在评论中显示数据。有什么想法或建议吗?

php html arrays sorting listitem
2个回答
3
投票

foreach($someArray as $key => $value)

将允许您获取数组的键和值。

还可以使用以下语法获取数组中的条目:

$a = array("foo"=>"Bar");
echo "The value at foo is ".$a['foo'];

您的尝试可以用上面的内容进行更新以获得您需要的结果(请记住您已经知道

$value
在您的示例中是一个数组)。


0
投票

首先,您需要按价格对列表进行排序,我建议使用 http://php.net/usort 为此。 整理好排序后,基本上就可以循环遍历结果来打印了

function cakeList ($cakes)
{
    echo '<ul>';
    foreach ($cakes as $cake => $details)
    {
        echo '<li>' . $cake . '<br/>' . $details['flavour'] . '<li/>';
    }
    echo '</ul>';
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.