1

Any way to sort the below array by the value it contains in the order field?

$line = array(
  0 => array(
    0 => array('order' => 3)
  ),
  1 => array(
    0 => array('order' => 1)
  ),
  2 => array(
    0 => array('order' => 2)
  ),
);

Required output -

$line = array(
    0 => array(
      0 => array('order' => 1)
    ),
    1 => array(
      0 => array('order' => 2)
    ),
    2 => array(
      0 => array('order' => 3)
    ),
  );

tried the below code but it does not work -

uasort($line, function($a, $b) {
    return $a['entity_id'] - $b['entity_id'];
  });

Update - The keys in all the above arrays are not-known, just written here for an eg.

2 Answers 2

2

Use the below code -

usort($line, function($a, $b) {
    return current($a)['order'] - current($b)['order'];
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It worked, I am not able to upvote, can only accept the answer.
1
uasort($line, function($a, $b) {
    return array_shift($a)['order'] <=> array_shift($b)[0]['order'];
});

6 Comments

the keys keep on changing and not necessarily 0.
is it only one value (one subarray) in this parent array?
yes, the format is same, just the keys are different
Here you go. Just grab array value of subarray. Thanks php isn't c++, python or go, so changing array values inside callback scope wouldn't affect original array.
Its supported in PHP7. last PHP5 (5.6) is already passed End of Lifecycle, and not recommended to be used. You can repalce <=> with > with almost same effect.
|

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.