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

问题描述 投票:0回答:1
[
    {
        "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到多维数组的代码。我无法弄清楚如何正确地构造它,所以我可以循环国家名称创建一个计数器变量,然后存储奖牌的数量。

php multidimensional-array
1个回答
0
投票

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

    <?php
    $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"
    }
]';

$json = json_decode($array,true);
$countries = array_column($json, 'country'); // Get countries in to another array
// Then sort according to the names in above countries array ASC
call_user_func_array('array_multisort', array($countries, SORT_ASC, SORT_STRING, &$json)); 

print_r($json);
?>
© www.soinside.com 2019 - 2024. All rights reserved.