显示基于另一个数组排序的数组

时间:2014-05-23 06:53:24

标签: php arrays

我有2个阵列

Array 1 : $agents = Array('abc','xyz','pqr');
Array 2 : $tot_calls = Array ('10','5','20');

此处,数组2分别反映了$ agents数组中代理进行的总呼叫。 代理人abc拨打了10个电话,代理人xyz拨打了5个电话,依此类推。

我希望结果数组显示按其调用次数排序(DESCENDING)的代理

$result = Array('pqr','abc','xyz'); //这里生成的数组按照它们所做的最大调用进行排序。

2 个答案:

答案 0 :(得分:2)

您可以在这种特殊情况下array_combine()合并krsort()。考虑这个例子:

$agents = Array('abc','xyz','pqr');
$tot_calls = Array ('10','5','20');
// calls become the keys and agents become the values
$sorted_values = array_combine($tot_calls, $agents);
krsort($sorted_values); // sort them by keys

print_r($sorted_values);

// maybe if you want to clear the keys
$sorted_values = array_values($sorted_values);

Sample Fiddle

编辑:

或者,@ Satish提出了一个很好的观点。避免相同的关键问题(也许,至少如果没有代理名称冲突)。你可以改用它(反过来说):

$agents = Array('abc','xyz','pqr');
$tot_calls = Array ('10','5','20');
// agents become keys and calls become values
$sorted_values = array_combine($agents, $tot_calls);
arsort($sorted_values);
$sorted_values = array_keys($sorted_values);

print_r($sorted_values);

Sample Fiddle

答案 1 :(得分:1)

试试这个

$agents = Array('abc','xyz','pqr');
$tot_calls = Array (10, 5, 20);

arsort($tot_calls);
foreach($tot_calls as $key=>$val)
{
  $arr_agents[] = $agents[$key];
}
print_r($arr_agents);

输出:

Array
(
    [0] => pqr
    [1] => abc
    [2] => xyz
)

<强> DEMO

DEMO-2

$agents = Array('abc','xyz','pqr','lmn');
$tot_calls = Array ('10', '5', '20', '5');

<强> OUTPUT-2:

Array
(
    [0] => pqr
    [1] => abc
    [2] => lmn
    [3] => xyz
)