PHP按ID排列“SELECT OPTIONS”

时间:2013-08-30 17:46:37

标签: php

我想知道我如何通过ID安排我的表格选项?

<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

1 个答案:

答案 0 :(得分: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>
...