我有一个看起来像这样的文件,它接收来自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']保持类别简单,中等,难度和极端。有没有办法可以让这个脚本按顺序输出类别:easy,medium,hard,extreme?
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
)
)
)
)
答案 0 :(得分: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");