[英]How to sort multi-dimensional array with bubble sort in PHP?
我的冒泡排序非常适合单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 . " ";
}
$pos_sql
返回:
Array
(
[0] => Array
(
[id] => 15
[protocol] => 12
[position] => 2
[subject_item] =>
[type] => D
[responsible] => Chonchol
[INSDATE] => 2019-07-03 11:33:13
[body] => With responsible
[participant] => Chonchol,Mahmud,more
[subject] => Check for multi-participant final
[status] => 0
)
[1] => Array
(
[id] => 16
[protocol] => 12
[position] => 2
[subject_item] =>
[type] => D
[responsible] => Mahmud
[INSDATE] => 2019-07-03 11:39:01
[body] => With Responsible
[participant] => Donald,Trump,Brad,Pitt
[subject] => Check for multi-participant final
[status] => 0
)
[2] => Array
(
[id] => 17
[protocol] => 12
[position] => 6
[subject_item] =>
[type] => I
[responsible] => Testing
[INSDATE] => 2019-07-03 11:43:01
[body] => Another body bcfb
[participant] =>
[subject] => Check for multi-participant final
[status] => 0
)
[3] => Array
(
[id] => 21
[protocol] => 12
[position] => 1
[subject_item] => This is form Update
[type] => S
[responsible] => three
[INSDATE] => 2019-07-13 04:39:10
[body] => ffffffffffff
[participant] =>
[subject] => Check for multi-participant final
[status] => 0
)
)
usort($arr, function ($a, $b) {
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++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j]['position'] > $arr[$j+1]['position']) {
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
}
}
}
工作演示 。
注意:我不知道为什么您需要气泡排序而不是usort()
。 usort()
简单得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.