在2D关联数组中使用多重排序来创建排名列表

时间:2013-07-28 09:29:48

标签: php arrays

以下代码组合了3个填充了网址和分数的数组,如果网址匹配,则将分数相加以创建新数组。我现在正在尝试按降序在组合数组中创建排名列表,但我不太确定如何做到这一点

<?php




$combined = array(); 

foreach($bingArray as $key=>$value){ // for each bing item
if(isset($combined[$key]))
    $combined[$key] += $value['score']; // add the score if already exists in $combined
else
    $combined[$key] = $value['score']; // set initial score if new
}

// do the same for google
foreach($googleArray as $key=>$value){
if(isset($combined[$key]))
    $combined[$key] += $value['score'];
else
    $combined[$key] = $value['score'];
}

// do the same for bing
foreach($bingArray as $key=>$value){
if(isset($combined[$key]))
    $combined[$key] += $value['score'];
else
    $combined[$key] = $value['score'];
}


array_multisort($value['score'], SORT_DESC,$combined);

print_r($combined); // print results  
?>

以下是我目前正在获得的输出

Warning: array_multisort() [function.array-multisort]: 
Argument #1 is an unknown sort flag in   /homepublic_html/agg_results.php on line   230
Array ( [time.com/time/] => 200 [time.gov/] => 297 [timeanddate.com/worldclock/] 
=> 294 [timeanddate.com/] => 194  [en.wikipedia.org/wiki/Time] => 289 
[worldtimezone.com/] => 190 [time100.time.com/]=> 188 
[time.gov/timezone.cgi?  Eastern/d/-5/java] 
=> 186    [en.wikipedia.org/wiki/Time_(magazine)] 
=> 275   [dictionary.reference.com/browse/time] => 182 [time.com/] 
=> 100 [time.com/time/magazine]
=> 96 [time.is/] => 95 [tycho.usno.navy.mil/cgi-bin/timer.pl] 
=> 94 [twitter.com/TIME]   => 93 [worldtimeserver.com/] => 92 ) 

任何帮助都是伟大的家伙和玩偶

2 个答案:

答案 0 :(得分:1)

[这应该是评论,但由于我的身份(声誉&lt; 50)我只能写帖子...]

我再次检查了php manual并发现对于您尝试执行的排序任务,函数array_multisort的第一个参数需要是一个与实际数组具有相同键的数组({ {1}})你想要排序。参数$combined不是一个数组,而只是一个存在于前一个$value循环范围内的变量。

您应该将代码修改为:

foreach

然后是:

$score=array();    
foreach($bingArray as $key=>$value){ // for each bing item
    if(!isset($score[$key])) { $score[$key]=0; }
    $score[$key] += $value['score'] // add the score to $score
    $combined[$key] = $value;       // place the whole associative array into $combined
    }

答案 1 :(得分:0)

我把这段代码放进去了

array_multisort($combined);
$reverse = array_reverse($combined, true);
print_r($reverse);

感谢您的帮助