0

我有一个看起来像这样的文件,它从 JSON 文件中获取数据并输出:

<?php
$game = "Test";
$itemsArray = json_decode(file_get_contents("http://test.com/stamps.json"), true);

echo "<table>";
echo "<tr><th>Image</th><th>Name</th><th>Difficulty</th><th>Description</th></tr>";

foreach ($itemsArray as $item) {
    $name = $item['name'];
    $stamps = $item['stamps'];

    if ($name == $game) {
        foreach ($stamps as $stampData) {

            $stampID = $stampData['stamp_id'];
            $stampName = $stampData['name'];
            $stampLevel = $stampData['rank_token'];
            $stampDescription = $stampData['description'];
            $stampMember = $stampData['is_member'];
            $stampID = $stampData['stamp_id'];

            if ($stampMember == "true") {
                $stampMember = "Yes";
            } else {
                $stampMember = "No";
            }

            echo "<tr>";

            echo "<td>";
            echo "Coming soon";
            echo "</td>";

            echo "<td>";
            print_r($stampName);
            echo "</td>";

            echo "<td>";
            print_r(ucwords($stampLevel));
            echo "</td>";

            echo "<td>";
            print_r($stampDescription.".");
            echo "</td>";

            echo "</tr>";

        }
    }
}

echo "</table>";
?>

但是,它会按照 JSON 文件中的顺序输出数据。这一切都混在一起了。

我想知道是否有一种方法可以按 $stampData['rank_token'] 持有的类别对输出进行排序。

$stampData['rank_token'] 包含简单、中等、困难和极端的类别。有没有办法让这个脚本按以下顺序输出类别:简单、中等、困难、极端?

JSON解码后数组的小例子:

Array
(
[13] => Array
        (
            [name] => Blah blah
            [description] => Blah blah blah
            [parent_group_id] => 8
            [display] => Blah : Blah
            [stamps] => Array
                (
                    [73] => Array
                        (
                            [stamp_id] => 73
                            [name] => Blah
                            [is_member] => 
                            [rank] => 1
                            [description] => Blah blah blah
                            [rank_token] => easy
                        )

                    [80] => Array
                        (
                            [stamp_id] => 80
                            [name] => Blah
                            [is_member] => 
                            [rank] => 2
                            [description] => Blah blah blah
                            [rank_token] => medium
                        )

                 )
          )
)
4

1 回答 1

0

查看 PHP 的 usort

function my_compare($a, $b) {
  if ($a["rank_token"] > $b["rank_token"]) return 1;
  if ($a["rank_token"] < $b["rank_token"]) return -1;
  return 0;
}

usort($stampData, "my_compare");
于 2013-03-12T21:15:36.097 回答