我有一个像这样的数组。
[Badi Assad] => Array
(
[last_name] => Assad
[first_name] => Badi
[artist_name] =>
[asterick] => *
[slug] => badiassad
)
[Ben Taylor] => Array
(
[last_name] => Taylor
[first_name] => Ben
[artist_name] => Ben Taylor
[asterick] => *
[slug] => bentaylor
)
[Beverly] => Array
(
[last_name] => Hills
[first_name] => Beverly
[artist_name] => Beverly
[asterick] =>
[slug] => Eedih
)
[Bruce Cockburn] => Array
(
[last_name] => Cockburn
[first_name] => Bruce
[artist_name] => Bruce Cockburn
[asterick] => *
[slug] => brucecockburn
)
[Bohème] => Array
(
[last_name] =>
[first_name] => Cassidy
[artist_name] => Bohème
[asterick] => *
[slug] => cassidy
)
我将如何进行排序,以便将姓氏和艺术家姓名按顺序排列,其中姓氏胜过艺术家名称,除非它是空的。
结果应该是这样的。
[Badi Assad] => Array
(
[last_name] => Assad
[first_name] => Badi
[artist_name] =>
[asterick] => *
[slug] => badiassad
)
[Bohème] => Array
(
[last_name] =>
[first_name] => Cassidy
[artist_name] => Bohème
[asterick] => *
[slug] => cassidy
)
[Bruce Cockburn] => Array
(
[last_name] => Cockburn
[first_name] => Bruce
[artist_name] => Bruce Cockburn
[asterick] => *
[slug] => brucecockburn
)
[Beverly] => Array
(
[last_name] => Hills
[first_name] => Beverly
[artist_name] => Beverly
[asterick] =>
[slug] => Eedih
)
[Ben Taylor] => Array
(
[last_name] => Taylor
[first_name] => Ben
[artist_name] => Ben Taylor
[asterick] => *
[slug] => bentaylor
)
我目前正在尝试这个。
$newartists = array();
foreach($users as $k => $v)
{
$name = (strlen($v['artist_name']) > 0) ? $v['artist_name'] : $v['first_name'].' '.$v['last_name'];
$newartists[$name]['last_name'] = $v['last_name'];
$newartists[$name]['first_name'] = $v['first_name'];
$newartists[$name]['artist_name'] = $v['artist_name'];
$newartists[$name]['asterick'] = $ask;
$newartists[$name]['slug'] = $v['slug'];
}
$sort = array();
foreach($newartists as $k=>$v) {
$sort['artist_name'][$k] = $v['artist_name'];
$sort['last_name'][$k] = $v['last_name'];
}
array_multisort( $sort['last_name'], SORT_ASC,$sort['artist_name'], SORT_ASC, $newartists);
谢谢!
答案 0 :(得分:1)
使用uasort function有点像这样:
<?php
$newartists = array(
'3' => array(
'last_name' => 'c',
'artist_name' => 'c'
),
'1' => array(
'artist_name' => 'a'
),
'2' => array(
'last_name' => 'b',
'artist_name' => 'd'
),
);
function cmp($a, $b)
{
$result = 0;
// Sort preferably by last name
if (!empty($a['last_name']) && !empty($b['last_name'])) {
$result = strcmp($a["last_name"], $b["last_name"]);
// Failover to artist name sort
} else {
$result = strcmp($a["artist_name"], $b["artist_name"]);
}
return $result;
}
usort($newartists, "cmp");
Array
(
[1] => Array
(
[artist_name] => a
)
[2] => Array
(
[last_name] => b
[artist_name] => d
)
[3] => Array
(
[last_name] => c
[artist_name] => c
)
)