1

I got an $actions array, and $actions_used array.

$actions_used looks like this:

array(1) {
  [2]=>
  string(1) "18"
  [5]=>
  string(1) "33"
}

$actions looks like this:

array(3) {
      [1]=>
      string(9) "Withdraw"
      [2]=>
      string(13) "Deposit"
      [5]=>
      string(10) "Blabla"
    }

I would like to sort $actions based on the value that is in $actions_used.

The correct output would be for $actions:

array(3) {
      [5]=>
      string(9) "Blabla"
      [2]=>
      string(13) "Deposit"
      [1]=>
      string(10) "Withdraw"
    }

Why? Because array key 5, "Blabla" has the biggest value "33" and then comes array key "2" which has value 18 and then at last comes array key 1, "Withdraw" which have 0 (no value)

How can this be done?

0

3 Answers 3

1

This should do the trick.

$sorted_actions = array();
asort($actions_used);
foreach($actions_used AS $key => $amount) {
  $sorted_actions[] = array('amount' => $amount, 'action' => $actions[$key]);
  unset($actions[$key]);
}
$sorted_actions = $sorted_actions + $actions;
0

How would something like this work?

arsort($action_used);
foreach ($action_used as $k => $v) {
    $newArray[$k] = $actions[$k];
    unset($action_used[$k];
}
$newArray = array_merge($newArray, $action_used);
1
  • This works but what about the rest of the actions, that are not in the actions_used? They are not in the $newArray Commented Sep 26, 2012 at 0:15
0

I think you could sort the second array with uksort and actually compare the values from the first array in the custom comparer

e.g.:

uksort($arr2, function($i1, $i2) {
    return $arr1[$i1] - $arr1[$i2];
});
0

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.