PHP嵌套数组

时间:2014-01-29 14:49:55

标签: php arrays

所以我被我的导师给了这个,完成我有点卡住了。我已经厌倦了大量的方法,但没有正确的方法来显示数据。

        <?php

        /*
        * 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)
        );

        /* print_r($cakes); */

        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中生成一个列表,以在评论中显示数据。有任何想法吗?或者建议你们在Stack溢出可以告诉我这是如何做的以及如何让它变得更好?

2 个答案:

答案 0 :(得分:3)

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

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

也可以使用以下语法抓取数组中的条目:

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

您可以使用上述内容更新您的尝试以获得所需的结果(请记住,您已经知道$value是您示例中的数组)。

答案 1 :(得分:0)

首先,您需要按价格对列表进行排序,我建议您使用http://php.net/usort。 在整理完排序后,您基本上可以循环结果以打印它们

function cakeList ($cakes)
{
    echo '<ul>';
    foreach ($cakes as $cake => $details)
    {
        echo '<li>' . $cake . '<br/>' . $details['flavour'] . '<li/>';
    }
    echo '</ul>';
}