在PHP中,我有这种数组(对不起这个大例子,但这是一个特定的类型):
[0] => Array
(
[title] => 1
[desc] => 2
)
[1] => Array
(
[title] => 1
[desc] => 3
)
[2] => Array
(
[title] => 1
[desc] => 2
[content] => 10
)
[3] => Array
(
[title] => 1
[desc] => 2
[content] => 11
)
[4] => Array
(
[title] => 1
[desc] => 3
[content] => 9
)
[5] => Array
(
[title] => 1
[desc] => 2
[content] => 10
[tag] => 'foo'
)
[6] => Array
(
[title] => 1
[desc] => 2
[content] => 10
[tag] => 'bar'
)
我想要这个输出:
[0] => Array
(
[title] => 1
[desc] => 2
)
[1] => Array
(
[title] => 1
[desc] => 2
[content] => 10
)
[2] => Array
(
[title] => 1
[desc] => 2
[content] => 10
[tag] => 'bar'
)
[3] => Array
(
[title] => 1
[desc] => 2
[content] => 10
[tag] => 'foo'
)
[4] => Array
(
[title] => 1
[desc] => 2
[content] => 11
)
[5] => Array
(
[title] => 1
[desc] => 3
)
[6] => Array
(
[title] => 1
[desc] => 3
[content] => 9
)
不幸的是,array_multisort()
无法使用非常数的键对数组进行排序:它只是忽略了所有数组......
有什么想法吗?
答案 0 :(得分:2)
我不清楚您想要订购哪种标准,但您可以使用usort
,为其提供定义比较的功能。
答案 1 :(得分:2)
您可以将usort
与定制的cmp
功能结合使用,以满足您的特殊需求,例如以下代码:
usort($arr, "cmp");
function cmp($a, $b) {
$array = array('title','desc','content','tag');
foreach ($array as &$ar) {
$ai = isset($a[$ar]);
$bi = isset($b[$ar]);
if ($ai && !$bi) {
return 1;
}
if ($bi && !$ai) {
return -1;
}
if (!$bi) {
return 0;
}
if ($a[$ar] > $b[$ar]) {
return 1;
}
if ($b[$ar] > $a[$ar]) {
return -1;
}
}
return 0;
}
应该做你想做的事。
答案 2 :(得分:0)
以下是示例代码的排序:
function cmp ($a, $b) {
if ($a['desc'] == $b['desc']) {
if (!isset($a['content']) && !isset($b['content'])) {
return 0;
}
else if (!isset($a['content'])) {
return -1;
}
else if (!isset($b['content'])) {
return 1;
}
else {
if ($a['content'] == $b['content']) {
if (!isset($a['tag'])) {
return -1;
}
else if (!isset($b['tag'])) {
return 1;
}
else {
if ($a['tag'] == $b['tag']) {
return 0;
}
else if ($a['tag'] < $b['tag']) {
return -1;
}
else {
return 1;
}
}
return 0;
}
else if ($a['content'] < $b['content']) {
return -1;
}
else {
return 1;
}
}
return 0;
}
else if ($a['desc'] < $b['desc']) {
return -1;
}
else {
return 1;
}
}
usort($array, 'cmp');
感谢 @Nelson,@ fromherehere和@xdazz 让我加入usort()
:)