按值对两级多维数组进行排序

时间:2023-01-11 21:34:07

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 个解决方案

#1


2  

Use the below code -

使用以下代码 -

usort($line, function($a, $b) {
    return current($a)['order'] - current($b)['order'];
});

#2


1  

uasort($line, function($a, $b) {
    return array_shift($a)['order'] <=> array_shift($b)[0]['order'];
});

#1


2  

Use the below code -

使用以下代码 -

usort($line, function($a, $b) {
    return current($a)['order'] - current($b)['order'];
});

#2


1  

uasort($line, function($a, $b) {
    return array_shift($a)['order'] <=> array_shift($b)[0]['order'];
});