[英]Using usort() on multidimensional alphanumeric array (numbers first)
這是我嘗試排序的示例數組:
$array = (object)array(
'this' => 'that',
'posts'=> array(
'title' => '001 Chair',
'title' => 'AC43 Table',
'title' => '0440 Recliner',
'title' => 'B419',
'title' => 'C10 Chair',
'title' => '320 Bed',
'title' => '0114'
),
'that' => 'this'
);
usort($array->posts, 'my_post_sort');
這是我用來排序的函數:
function my_post_sort($a, $b) {
$akey = $a->title;
if (preg_match('/^[0-9]*$',$akey,$matches)) {
$akey = sprintf('%010d ',$matches[0]) . $akey;
}
$bkey = $b->title;
if (preg_match('/^[0-9]*$',$bkey,$matches)) {
$bkey = sprintf('%010d ',$matches[0]) . $bkey;
}
if ($akey == $bkey) {
return 0;
}
return ($akey > $bkey) ? -1 : 1;
}
這給了我以下結果:
'posts', array(
'title' => 'C10 Chair',
'title' => 'B419',
'title' => 'AC43 Table',
'title' => '320 Bed',
'title' => '0440 Recliner',
'title' => '0114',
'title' => '001 Chair'
)
現在,我需要的最后一步是讓數字出現在字母(降序)之前(降序)。
這是我想要的輸出:
'posts', array(
'title' => '320 Bed',
'title' => '0440 Recliner',
'title' => '0114',
'title' => '001 Chair',
'title' => 'C10 Chair',
'title' => 'B419',
'title' => 'AC43'
)
各種sorts、uasorts、preg_match等函數都試過了; 並且似乎無法弄清楚最后一步。
有什么建議或幫助嗎? 謝謝你。
試試這個比較功能:
function my_post_sort($a, $b) {
$akey = $a->title;
$bkey = $b->title;
$diga = preg_match("/^[0-9]/", $akey);
$digb = preg_match("/^[0-9]/", $bkey);
if($diga && !$digb) {
return -1;
}
if(!$diga && $digb) {
return 1;
}
return -strcmp($akey, $bkey);
}
它將按降序排序,但將數字放在其他符號之前。
首先,我不認為你的數組可以工作......你不能在同一個數組級別上多次使用相同的鍵。
foreach ($array as $key => $title) {
if ( is_numeric(substr($title, 0, 1)) ) {
$new_array[$key] = $title;
}
}
array_multisort($array, SORT_DESC, SORT_STRING);
array_multisort($new_array, SORT_DESC, SORT_NUMERIC);
$sorted_array = array_merge($array, $new_array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.