按字母顺序组织阵列输出

时间:2016-02-15 21:55:28

标签: php arrays foreach

我尝试了多种方法但没有成功,无论如何我可以组织下面的结果,因此结果是按字母顺序排列的吗?

<?php
    $datas = array_slice($facilities, 0, $leftoshownumber);
    foreach($datas as $data) {
        if(in_array ($data->Name,$removedouble)) continue; 
        echo '<div class="checkmark-33"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">'. $data->Name .'</div></div>'; 
    }; 
?> 

任何帮助都会很棒,谢谢!

2 个答案:

答案 0 :(得分:1)

在您的代码中,$datas是一个对象数组,每个单独的$data对象都包含一个“名称”字段。因此,您需要根据每个$datas字段的值按字母顺序对$data->Name数组进行排序。如问题Sort array of objects by object fields中所述,可以使用usort

完成此操作
<?php
    function cmp($a, $b) {
        return strcmp($a->Name, $b->Name);
    }

    $datas = array_slice($facilities, 0, $leftoshownumber);
    usort($datas, "cmp");

    foreach($datas as $data) {
        if(in_array ($data->Name,$removedouble)) continue; 
            echo '<div class="checkmark-33"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">'. $data->Name .'</div></div>'; 
    }; 
?> 

答案 1 :(得分:0)

您可以使用用户定义的排序usort

<?php 
    function cmp($a, $b){ // User defined sorting algorithm
        if ($a == $b)
            return 0;
        return ($a['name'] < $b['name']) ? -1 : 1;
    }
    $datas = array_slice($facilities, 0, $leftoshownumber);
    usort($datas, "cmp"); // use the function cmp() to do sorting comparison 
    foreach($datas as $data) {
        if(in_array ($data->Name,$removedouble)) continue; 
            echo '<div class="checkmark-33"><div class="fa-stack fa-1x checkmark-icon"><i class="fa fa-circle fa-stack-2x icon-background"></i><i class="fa fa-check fa-stack-1x icon-text"></i></div><div class="checkmark-inner">'. $data->Name .'</div></div>'; 
    }; 

?>