2014-05-29 13:16

# 使用两个值对数组进行排序

I am trying to sort an array using two values (order, sub_order) so that they are orders like 1.1, 1.2, 2.1, 2.1.

Below is an example of the array as it is now and the second is the array sorted correctly by the order and sub_order values.

``````Array
(
[0] => Array
(
[id] => 1
[order] => 1
[sub_order] => 2
[title] => Blah
)

[1] => Array
(
[id] => 3
[order] => 2
[sub_order] => 2
[title] => Blah
)

[2] => Array
(
[id] => 2
[order] => 1
[sub_order] => 1
[title] => Blah
)

[3] => Array
(
[id] => 4
[order] => 2
[sub_order] => 1
[title] => Blah
)

)
``````

Ordered correctly...

``````Array
(
[0] => Array
(
[id] => 2
[order] => 1
[sub_order] => 1
[title] => Blah
)

[1] => Array
(
[id] => 1
[order] => 1
[sub_order] => 2
[title] => Blah
)

[2] => Array
(
[id] => 4
[order] => 2
[sub_order] => 1
[title] => Blah
)

[3] => Array
(
[id] => 3
[order] => 2
[sub_order] => 2
[title] => Blah
)

)
``````

Any help would be great.

• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 邀请回答

#### 1条回答默认 最新

• duandao7704 2014-05-29 13:20
最佳回答

Use `usort`

``````usort(\$array, "order_sub_order_sort");
function order_sub_order_sort(\$a, \$b) {
if (\$a["order"] != \$b["order"]) {
return \$a["order"] - \$b["order"];
}
return \$a["sub_order"] - \$b["sub_order"]
}
``````

Change `\$a-\$b` for `\$b-\$a` if you want to sort the other way around. I always forget which is ascending and which is descending.

评论
解决 无用
打赏 举报