0

I have 2 arrays

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

Here array 2 reflects total calls made by agents in $agents array respectively. i.e Agent abc made 10 calls , Agent xyz made 5 calls and so on.

I want the resultant array to display agents sorted(DESCENDING) by the number of calls they made

i.e $result = Array('pqr','abc','xyz'); // Here the resulting array is sorted on the max calls they made.

2 Answers 2

2

You can combine array_combine() the krsort() on this particular situation. Consider this example:

$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

EDIT:

Alternatively, @Satish made a good point about it. To avoid the same key issue (well maybe, at least if there are no agent name collision). You can use this instead (just the other way around):

$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

Sign up to request clarification or add additional context in comments.

3 Comments

its wrong method what will happen if there is more users with same calls how will the same index in your array by array_combine.
what will happen if there is one more user with same calls like $agents = Array('abc','xyz','pqr', 'lmn'); $tot_calls = Array ('10','5','20','5');
@kevinabelita not right yet. see link of your code
1

try this

$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);

OUTPUT :

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

DEMO

DEMO-2 : with

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

OUTPUT-2:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.