我正在慢慢学习PHP,并且在通过foreach()循环进行排序时需要一些帮助。当前,此循环从数据库表中获取ID和名称,并将其显示在列表中,但是,我在按字母顺序对该列表进行排序时遇到了问题。这是现在的样子,在这里检索所有记录并将其显示在整洁的列表中:
<?php foreach ($disabilities as $disability):?>
<option value=<?=($disability->id)?>><?=($disability->name)?></option>
<?php endforeach; ?>
这就是我尝试过的:
<?php myArray = array($disabilities)
sort($disabilities)
foreach ($disabilities as $disability): ?>
<option value=<?=($disability->id)?>><?=($disability->name)?></option>
<?php endforeach; ?>
任何关于我是否走对路的提示将不胜感激!
答案 0 :(得分:0)
您可以通过两种方式实现这一目标。 1)在从数据库查询时对此进行排序。 2)在php中对数组进行排序,这是在php中进行排序的示例代码。
//stdclass object arrays to simple array
$disabilities = json_decode(json_encode($object), True);
$sortArray = array();
foreach($disabilities as $disability){
foreach($disability as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want to apply sorting for
array_multisort($sortArray[$orderby], SORT_ASC, $disabilities);
希望它对您有用
编辑:当我将其从stdClass对象更改为数组时,您将像这样回显
echo $disability['name'];
答案 1 :(得分:0)
您可以使用PHP usort函数添加用户定义的比较函数。
$obj = (object) array(
['id' => '1', 'name' => 'Ronda'],
['id' => '2', 'name' => 'Aba'],
['id' => '3', 'name' => 'Mac']
);
//convert obj to array usort only accept array
$disabilities = json_decode(json_encode($obj), true);
//define custom function
function sortByName($a, $b) {
//compare two strings
return strcmp($a['name'], $b['name']);
}
//sort using usort before use
usort($disabilities, 'sortByName');
//output
Array ( [0] => Array ( [id] => 2 [name] => Aba ) [1] => Array ( [id] => 3 [name] => Mac ) [2] => Array ( [id] => 1 [name] => Ronda ) )
有效的演示:https://repl.it/repls/GruesomeExaltedDevicedriver,对数组进行排序后,您可以直接在foreach
中使用。