FanaticD
FanaticD

Reputation: 1467

Two dependent arrays, need to sort by elements of the first one

I know this is definitively a bad design, but at this moment, it is the only way how I can figure this out.

I have two arrays. One filled with string values, second one with integers for instance:

$array01 = array("apple", "bannana", "orange", "plum", "kiwi", "kiwi");
$array02 = array(2, 4, 3, 2, 1, 2);

Values are linked to each other.

apple - 2, bannana - 4, orange - 3, plum - 2, kiwi - 1, kiwi - 2.

As shown, values in each array may be duplicated (I can't remove redundance).

I need to sort the first array by alphabet ascending - but as you already know - I need to shake with the second array exactly as I shake with first array in order to sort it, so the values will match after the sort.

My question: Is there an easy way to do this? Or I simply have to write my own sort algorhytm? Note that I can not use any external libraries.

Thanks in advance!

Upvotes: 1

Views: 149

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

I use array_multisort. For your case, since SORT_ASC is the default:

array_multisort($array01, $array02);

If you could deal with a different array structure (couldn't resist):

array_multisort(array_column($result = array_map(null, $array01, $array02), 0), $result);

Result:

Array
(
[0] => Array
    (
        [0] => apple
        [1] => 2
    )

[1] => Array
    (
        [0] => bannana
        [1] => 4
    )

[2] => Array
    (
        [0] => kiwi
        [1] => 1
    )

[3] => Array
    (
        [0] => kiwi
        [1] => 2
    )

[4] => Array
    (
        [0] => orange
        [1] => 3
    )

[5] => Array
    (
        [0] => plum
        [1] => 2
    )
)

Upvotes: 3

Curtis
Curtis

Reputation: 5892

The easiest way would be to put the values as value pairs into an array. Then sort on the string portion of the value pair. The integer portion would stay with the same string portion because you paired them.

Upvotes: 0

Related Questions