1

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?

2
  • Please make a little example from your input and your expected output Commented Jun 10, 2015 at 19:50
  • So where are we with this question ? Commented Jun 10, 2015 at 20:33

1 Answer 1

4

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
        )

)
Sign up to request clarification or add additional context in comments.

4 Comments

how could I apply this is a collection of arrays?
@Emanegux What do you mean with this? If you have multiple arrays?
If I have $matrix['label3'] and $matrix['label4'] and so on and wanted them to be sorted in the same way $matrix['label2'] was sorted
@Emanegux Just use call_user_func_array() and pass all sub-Arrays as arguments by reference, e.g. call_user_func_array("array_multisort", [&$matrix["label1"], &$matrix["label2"], &$matrix["label3"], ...]);

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.