2014-08-27 94 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);