-1

Does anyone know how to sort an associative array into alternating largest smallest values? In other words, the odd positioned element (1st, 3rd, 5th, etc) should be ordered descending and the even positioned elements (2nd, 4th, 6th, etc) should be ordered ascending.

I.E.

array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7)

Should become:

array("E"=>30, "D"=>1, "A"=>10, "F"=>1, "G"=>7, "B"=>2, "C"=>5)
5
  • I don't see any algorithm of sorting in the result example. Could you point to it, please? Commented Nov 29, 2012 at 11:38
  • I think largest,smallest,secondlargest,secondsmallest etc. etc. Commented Nov 29, 2012 at 11:40
  • Well what is the problem? First you sort the array ascending or descending, whatever, next you iterate over it and construct the output array in any order you want. Commented Nov 29, 2012 at 11:40
  • Huh? That's what I'm asking! How do I achieve it? Commented Nov 29, 2012 at 11:41
  • You iterate over a function whilst there are elements left in the sorted array. In each iteration you pop the last/first element from the array depending on if the key is even/uneven. That what you mean? Commented Nov 29, 2012 at 11:43

2 Answers 2

2

Based on the answer to your previous version of this question:

$myArray = array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7);
asort($myArray);
$myArrayKeys = array_keys($myArray);

$newArray = array();
while (!empty($myArray)) {
    $newArray[array_shift($myArrayKeys)] = array_shift($myArray);
    if (!empty($myArray))
        $newArray[array_pop($myArrayKeys)] = array_pop($myArray);
}
var_dump($newArray);

or, if you want largest first:

$myArray = array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7);
asort($myArray);
$myArrayKeys = array_keys($myArray);

$newArray = array();
while (!empty($myArray)) {
    $newArray[array_pop($myArrayKeys)] = array_pop($myArray);
    if (!empty($myArray))
        $newArray[array_shift($myArrayKeys)] = array_shift($myArray);
}
var_dump($newArray);
Sign up to request clarification or add additional context in comments.

Comments

0

Simply sort the input array in a descending direction (preserving keys), then at every second element, move all remaining elements except for the last element to the end of the array.

Code: (Demo)

$array = ["A" => 10, "B" => 2, "C" => 5, "D" => 1, "E" => 30, "F" => 1, "G" => 7];
arsort($array);
for ($i = 1, $count = count($array); $i < $count; $i += 2) {
    $array += array_splice($array, $i, -1);
}
var_export($array);

Output:

array (
  'E' => 30,
  'F' => 1,
  'A' => 10,
  'D' => 1,
  'G' => 7,
  'B' => 2,
  'C' => 5,
)

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.