0

我想知道如何通过 ID 以 php 的形式排列我的选项?

<option value="9171">Name1</option>
<option value="5063">Name1</option>
<option value="6167">Name1</option>
<option value="5208">Name1</option>
<option value="4917">Name1</option>
<option value="4938">Name1</option>
<option value="6193">Name1</option>
<option value="6192">Name1</option>
<option value="5342">Name1</option>
<option value="6157">Name1</option>
<option value="5228">Name1</option>
<option value="2126">Name1</option>
<option value="1668">Name1</option>
<option value="6186">Name1</option>
<option value="5343">Name1</option>
<option value="4915">Name1</option>
<option value="9217">Name1</option>
<option value="7160">Name1</option>
<option value="9025">Name1</option>
<option value="9066">Name1</option>
<option value="9092">Name1</option>

从 PHP 中,我如何按 ID 顺序排列?ID 是选项的值。我从 media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json 获取 IDS

4

1 回答 1

1

编辑:如果你真的必须对<option/>列表进行排序,你可以这样做:

$options = <<<EOD
<option value="4917">Name1</option>
<option value="4938">Name1</option>
<option value="6193">Name1</option>
<option value="22">Name1</option>
<option value="5342">Name1</option>
<option value="6157">Name1</option>
<option value="7160">Name1</option>
<option value="9025">Name1</option>
<option value="9066">Name1</option>
<option value="1">Name1</option>
EOD;

$optionsArray = explode("\n", $options);
natsort($optionsArray);

print_r($optionsArray);

结果:

Array
(
    [9] => <option value="1">Name1</option>
    [3] => <option value="22">Name1</option>
    [0] => <option value="4917">Name1</option>
    ...
)

请注意natsort,它确保122值正确排序。

编辑结束

// $json = file_get_contents('http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json');
$json = file_get_contents('paper_items.json');
$items = json_decode($json);

// sort by paper_item_id by keying by it
foreach ($items as $item)
{
    $ordered[$item->paper_item_id] = $item;
}

// output options sorted by paper_item_id
$options = '';
foreach ($ordered as $id => $item)
{
    $options .= "<option value=\"$id\">$item->label</option>\n";
}

print $options;

结果:

<option value="1">Blue</option>
<option value="2">Green</option>
<option value="3">Pink</option>
<option value="4">Black</option>
<option value="5">Red</option>
...
于 2013-08-30T19:21:03.907 回答