を使用してusort()
、整数値も含む文字列を並べ替えることができますか?
たとえば、電子メール アドレス (およびその他のデータ) を含むオブジェクトの配列を見てみましょう。
$invitees = Array(
[0] => Array(
'email' => 'test11@testing.com'
),
[1] => Array(
'email' => 'test2@testing.com'
),
[2] => Array(
'email' => 'test1@testing.com'
)
);
次のコードを使用すると、配列要素が単純な文字列として比較されます -
/** Sort the data (if the sort key is defined) */
if(!empty($_REQUEST['orderby'])) :
usort($emails, array(&$this, '_order_callback'));
endif;
function _order_callback($item_a, $item_b){
/** Grab 'orderby', which must have been set for this function to be called */
$orderby = $_REQUEST['orderby'];
/** If no 'order' is not set, default to ASC */
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'ASC';
$result = strcmp($item_a[$orderby], $item_b[$orderby]);
return (strtoupper($order) === 'ASC') ? $result : -$result; //Send final sort direction to usort
}
結果は次の順序で配信されます -
[0] - 'test11@testing.com'
[2] - 'test1@testing.com'
[1] - 'test2@testing.com'
私はこの順序を望んでいますが -
[2] - 'test1@testing.com'
[1] - 'test2@testing.com'
[0] - 'test11@testing.com'
これは可能usort()
ですか?ありがとう。
編集
natsort()
(以下のコメント/回答のおかげで)の存在を知ったので、これを見つけて試すことができました-
$result = ($item_a[$orderby] > $item_b[$orderby] ? 1 : ($item_a[$orderby] < $item_b[$orderby] ? -1 : 0));
その比較を_order_callback()
関数 ( if $orderby === email
) に追加しましたが、近いですが、 order でソートされ11, 12, 13, 14, 1, 2, 3, 4
ます。