1

I have an array that looks something like below, but it could potentially contain more drafts.

$multi_arr = array(
    'draft1' => array (
        'alloc_coeff' => 560,
        'steps_count' => 2,
        'order_draft' => array(
            '0' => array(
                'whse_id' => 4,
                'quantity' => 0,
                'percent' => 0
            ),
            '1' => array(
                'whse_id' => 1,
                'quantity' => 10,
                'percent' => 66.666666666667
            )           
        )
    ),
    'draft2' => array (
        'alloc_coeff' => 1517,
        'steps_count' => 1,
        'order_draft' => array(
            '0' => array(
                'whse_id' => 1,
                'quantity' => 10,
                'percent' => 66.666666666667
            )      
        )
    ),
    'draft3' => array (
        'alloc_coeff' => 559,
        'steps_count' => 2,
        'order_draft' => array(
            '0' => array(
                'whse_id' => 2,
                'quantity' => 0,
                'percent' => 0
            ),
            '1' => array(
                'whse_id' => 1,
                'quantity' => 10,
                'percent' => 66.666666666667
            )           
        )
    )
);

I need to sort the content by using two variables: alloc_coeff and steps_count.

First alloc_coeff needs to be considered from the highest to the lowest value.

And then as a second variable the steps_count from lowest value to highest.

usort($multi_arr, function($a, $b) {
    return $a['alloc_coeff'] <=> $b['alloc_coeff'];
});

I don't need the entire array to be rewritten and stored in a temporary variable, I just need the keys sorted like this (expected outcome) draft2, draft1 and lastly draft3.

What's a way to accomplish this?

1 Answer 1

1

You can do it like below:-

array_multisort(array_column($multi_arr, 'alloc_coeff'), SORT_DESC,
                array_column($multi_arr, 'steps_count'), SORT_ASC,
                $multi_arr);

Output:- https://eval.in/924894 And https://eval.in/924892

Note:- tested in 5.6.23 and PHP 7.0.8

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

2 Comments

Wow! That is so simple! Thanks.
@Borsn glad to help you :):)

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.