如何在PHP中使用冒泡排序对多维数组进行排序?

我的冒泡排序非常适合 single array。我如何为多维实现这个array?我想对这个多维数组值进行排序['position']。


代码:


$itemId = $parentTicket[0]['id'];


function bubbleSort(&$arr)

{

    $n = sizeof($arr);


    for($i = 0; $i < $n; $i++)

    {

        for ($j = 0; $j < $n - $i - 1; $j++)

        {

            if ($arr[$j] > $arr[$j+1])

            {

                $t = $arr[$j];

                $arr[$j] = $arr[$j+1];

                $arr[$j+1] = $t;

            }

        }

    }

}


$sql = "SELECT item.id, item.protocol, item.position, item.subject_item, item.type, item.responsible, item.INSDATE, item.body, pp.participant, p.subject, p.status FROM protocol p LEFT JOIN protocol_item item ON item.protocol = p.id LEFT JOIN protocol_participant pp ON pp.itemid = item.id WHERE item.protocol = $itemId GROUP BY item.id";

$arr = $global->db->getQuery($sql);

//$arr = array(64, 34, 25, 12, 22, 11, 90); // it's working


$len = sizeof($arr);

bubbleSort($arr);


echo "Sorted array : \n";


for ($i = 0; $i < $len; $i++) {

     $final_position = $arr[$i];

     echo $final_position . " ";


}


ITMISS
浏览 224回答 1
1回答

达令说

使用usort ()你可以做到这一点。工作演示。usort($arr, function ($a, $b) {&nbsp; &nbsp; return $a['position'] > $b['position'] ? 1 : -1;});print '<pre>';print_r($arr);在冒泡排序的帮助下。在您的代码中,您应该与两个位置进行比较,但您的比较是与数组索引进行比较。需要稍作修改:更改$arr[$j] > $arr[$j+1]为$arr[$j]['position'] > $arr[$j+1]['position'].$n = sizeof($arr);for($i = 0; $i < $n; $i++) {&nbsp; &nbsp; for ($j = 0; $j < $n - $i - 1; $j++) {&nbsp; &nbsp; &nbsp; &nbsp; if ($arr[$j]['position'] > $arr[$j+1]['position']) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $t = $arr[$j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arr[$j] = $arr[$j+1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arr[$j+1] = $t;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}工作演示。注意:我不知道为什么你需要冒泡排序而不是usort(). usort()简单得多。
打开App,查看更多内容
随时随地看视频慕课网APP