我从
获得两个数组$check = getmxrr ( $domain, $mxhosts, $weight );
我希望将mxhosts放在第三个数组中,从最低到最高权重。
为简单起见,我们有简单的数组名称和值:
$s = array('slowest','fast','very slow', 'slow','very fast', 'fastest');
$n = array( 40, 10, 30, 20, 5, 0 );
现在,使用此代码,我可以获得我正在寻找的有序数组:
$o = array_combine($n, $s);
ksort($o);
但是,如果元素具有相同的权重,则只有具有重复权重的最后一个元素才会出现在有序数组中。
是否有任何类似(低占用空间)的解决方案没有这个问题?
说明性案例如下。
重量值是唯一的。输出正常:
[0] => fastest [5] => very fast [10] => fast [20] => slow [30] => very slow [40] => slowest
我们有相同重量的元素。输出不正常(快速消失):
$n = array( 40, 10, 30, 10, 20, 5, 0 );
$s = array('slowest','fast','very slow','fast2', 'slow','very fast', 'fastest');
[0] => fastest [5] => very fast [10] => fast2 [20] => slow [30] => very slow [40] => slowest
答案 0 :(得分:2)
由于您认为主机名是唯一的,因此请切换组合的顺序
$n = array( 40, 10, 30, 10, 20, 5, 0 );
$s = array('slowest','fast','very slow','fast2', 'slow','very fast', 'fastest');
$o = array_combine($s, $n);
并使用asort在保持键的同时对值进行排序
asort($o);
比排序的主机名在array_keys
中var_dump(array_keys($o));
array(7) {
[0]=>
string(7) "fastest"
[1]=>
string(9) "very fast"
[2]=>
string(5) "fast2"
[3]=>
string(4) "fast"
[4]=>
string(4) "slow"
[5]=>
string(9) "very slow"
[6]=>
string(7) "slowest"
}
var_dump($o);
array(7) {
["fastest"]=>
int(0)
["very fast"]=>
int(5)
["fast2"]=>
int(10)
["fast"]=>
int(10)
["slow"]=>
int(20)
["very slow"]=>
int(30)
["slowest"]=>
int(40)
}
答案 1 :(得分:1)
你可以这样做:
$s = array('slowest','fast', 'slow', 'fastest', 'slow 2');
$n = array( 40, 10, 20, 0, 20);
$res = array();
foreach ($n as $k => $v) {
$res[$v] .= count($res[$v]) ? ",{$s[$k]}" : $s[$k];
}
ksort($res);
$res = explode(',', implode(',', $res));
print_r($res);
/*
Array
(
[0] => fastest
[1] => fast
[2] => slow
[3] => slow 2
[4] => slowest
)
*/
答案 2 :(得分:0)
试试这个
function cmp($a, $b)
{
if ($a > $b)
return 1;
elseif ($b > $a)
return -1;
else
return 0;
}
uksort($array, 'cmp');