JSON至PHP中的多维数组并按键排序

时间:2018-09-05 14:37:37

标签: php multidimensional-array

[
    {
        "competitorName": "Usain Bolt",
        "country": "Jamaica",
        "event": "100m",
        "medalWon": "G",
        "worldRecord": "Y"
    },
    {
        "competitorName": "Dave Batista",
        "country": "United States",
        "event": "Wrestling",
        "medalWon": "G",
        "worldRecord": "Y"
    },
    {
        "competitorName": "Leonel Messi",
        "country": "Argentina",
        "event": "Soccer \/ Football",
        "medalWon": "G",
        "worldRecord": "N"
    },
    {
        "competitorName": "Angel Di Maria",
        "country": "Argentina",
        "event": "Soccer \/ Football",
        "medalWon": "G",
        "worldRecord": "N"
    }
]

我需要将其放在表格中,并按获得奖牌最多的国家/地区进行排序,并输出计数和奖牌。

$form = file_get_contents("data.json");
$data = json_decode($form,true);

<section>
<div class="container">
    <div class="row">
        <div class="col col-md-6">
            <ul><br>
                <?php foreach($data as $country) { 

                    echo "<li>". $country['country']. " has the following medal in " .$country['event']. "</li>";
                    echo "<li>".$country['competitorName']. "</li>";
                    echo "<li>".$country['medalWon']. "</li>";
                    foreach($country as $key => $value) {

                        }
                        echo "<br>";

                    }?>
                </ul>
            </div>
        </div>
    </div>
</section>

这是到目前为止,我拥有的数据是从json到多维数组的代码。我不知道如何正确地构造它,所以我可以为国家名称循环创建一个计数器变量,然后存储奖牌数。

1 个答案:

答案 0 :(得分:0)

您可以使用数组列(键)对数组进行排序,

let exercise = Exercise(context: context)
            exercise.id = Int16(e["id"]!)!
            exercise.name = e["name"]      // ok because string field
            exercise.level = Int16(e["level"]!)!
            // and so on for other 20 fields....