Karem
Karem

Reputation: 18103

Sort an array from another array values in PHP

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?

Upvotes: 1

Views: 73

Answers (3)

StrubT
StrubT

Reputation: 1028

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];
});

Upvotes: 0

David
David

Reputation: 2065

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;

Upvotes: 1

Tim S
Tim S

Reputation: 5101

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

Upvotes: 0

Related Questions