2014-08-27 173 views
0

我有一個數組,看起來像這樣:排序陣列基於數量價值

Array 
(
    [0] => [email protected] 20140827 
    [1] => [email protected] 20130827 
    [2] => [email protected] 20140825 
    [3] => [email protected] 20120825 
    [4] => [email protected] 20140826 
) 

現在我想排序此數組中的PHP基於數字只有這麼忽略了排序的電子郵件住址處理。

+2

你看看在[排序功能列表]需要(http://php.net/manual/en/array.sorting.php)的排序該手冊,看看他們有沒有可以幫助你? – Jon 2014-08-27 11:48:23

+0

ksort可以幫助你:http://php.net/manual/en/function.ksort.php – Logar 2014-08-27 11:48:54

+1

@Logar:'ksort'不能幫到這裏。 – Jon 2014-08-27 11:49:27

回答

1
<?php 
$data = Array(0 => '[email protected] 20140827', 
    1 => '[email protected] 20130827', 
    2 => '[email protected] 20140825', 
    3 => '[email protected] 20120825', 
    4 => '[email protected] 20140826' 
); 

$count_data = count($data); 

for($i=0;$i<$count_data;$i++) 
{ 
    $new_data[trim(strstr($data[$i], ' '))]=$data[$i]; 
} 
echo "<pre>"; print_r($new_data); 
?> 

這將返回

Array 
(
    [20140827] => [email protected] 20140827 
    [20130827] => [email protected] 20130827 
    [20140825] => [email protected] 20140825 
    [20120825] => [email protected] 20120825 
    [20140826] => [email protected] 20140826 
) 

現在,您可以根據主要

0

你可以通過數組循環,explode上的空間,' '字符串,然後設置第一部分$explodedString[1]作爲新陣列的關鍵,那麼新的陣列上使用ksort

未經測試的代碼。

$oldArr; 
$newArr = array(); 

foreach($oldArr as $oldStr){ 
    $tmpStr = explode(' ', $oldStr); 
    $newArr[$tmpStr[1]] = $tmp[0]; //You could use $oldStr if you still needed the numbers. 
} 

ksort($newArr); 
4

例如,假設條目總是喜歡email space number

usort($ary, function($a, $b) { 
    $a = intval(explode(' ', $a)[1]); 
    $b = intval(explode(' ', $b)[1]); 
    return $a - $b; 
}); 

或更復雜但有效的方式使用Schwartzian transform

$ary = array_map(function($x) { 
    return [intval(explode(' ', $x)[1]), $x]; 
}, $ary); 

sort($ary); 

$ary = array_map(function($x) { 
    return $x[1]; 
}, $ary);