Emanegux
Emanegux

Reputation: 1120

How can I sort one array depending on another array?

I have two arrays stored in an array. They have the same number of values and are aligned:

$matrix['label1']
$matrix['label2']

I want to apply alphabetical sorting to $matrix['label1'] and move the contents of $matrix['label1'] in the same pattern. Here is an example of input and output.

$matrix['label1'] = ['b','c','a']
$matrix['label2'] = [ 1, 2, 3]

asort($matrix['label1'])
// outputs ['a','b','c']
//$matrix['label2'] should now be depending on that [ 3, 1, 2] 

How can I change my asort() call to get this to work?

Upvotes: 1

Views: 54

Answers (1)

Rizier123
Rizier123

Reputation: 59681

You are looking for array_multisort(), just pass both subArrays as arguments to it:

<?php

    $matrix['label1'] = ['b','c','a'];
    $matrix['label2'] = [ 1, 2, 3];

    array_multisort($matrix['label1'], $matrix['label2']);
    print_r($matrix);

?>

output:

Array
(
    [label1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

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

)

Upvotes: 4

Related Questions