Array_multisort找不到我的关联键

时间:2014-10-14 08:49:26

标签: php arrays sorting

我试图根据我创建的元素序列对数组的键进行排序。

以下是我的数组示例:

[
 {
 -14297: [
     -{
         waypoint_id: "14297"
         sequence: 27
         order_id: 12271
      }
    ]
 -34502: [
     -{
         waypoint_id: "34502"
         sequence: 19
         order_id: 30484

      },
     -{
         waypoint_id: "345202"
         sequence: 19
         order_id: 433

      }
  ]

到目前为止,我已尝试过这样做:

    $sort = array();
    foreach($myArr as $k=>$v) {
        $sort['sequence'][$k] = $v['sequence'];

    }
    array_multisort($sort['sequence'], SORT_ASC, $myArr );

但我一直收到一个错误的序列'没有定义。

我的预期产出如下:

[
 -34502: [
     -{
         waypoint_id: "34502"
         sequence: 19
         order_id: 30484

      },
     -{
         waypoint_id: "345202"
         sequence: 19
         order_id: 433

      }

  -14297: [
     -{
         waypoint_id: "14297"
         sequence: 27
         order_id: 12271
      }
    ]

  ]

注意:这是一个json对象。我正在返回$ myArr;

print_r给了我这个:

Array
(
    [36862] => Array
        (
            [0] => Array
                (
                    [waypoint_id] => 36862
                    [sequence] => 1
                    [order_id] => 32628

                )

        )

    [35633] => Array
        (
            [0] => Array
                (
                    [waypoint_id] => 35633
                    [sequence] => 2
                    [order_id] => 31452

                ),
            [1] => Array
                (
                    [waypoint_id] => 35633
                    [sequence] => 2
                    [order_id] => 34343

                )

        )

这给了我正确的回报..

1 个答案:

答案 0 :(得分:0)

因此,如果您可以为阵列提供一个结构,那么下面的示例应该可以很好地为您完成。

Unsortet Array

$array = new ArrayIterator([
    [
        'element_id' => 34502,
        'waypoint_id' => 34502,
        'sequence' => 19,
        'order_id' => 30484
    ],
    [
        'element_id' => 34502,
        'waypoint_id' => 345202,
        'sequence' => 19,
        'order_id' => 433
    ],
    [
        'element_id' => 14297,
        'waypoint_id' => 14297,
        'sequence' => 27,
        'order_id' => 12271
    ]
]);

使用PHP自己的SPL库的SplMinHeap类,您可以按顺序对数组进行排序

class SequenceMinHeap extends SplMinHeap {
    public function compare($sequence1, $sequence2) {
        return $sequence2['sequence'] - $sequence1['sequence'];
    }
}

$result = new SequenceMinHeap();
while ($array->valid()) {
    $result->insert($array->current());
    $array->next();
}

请记住,这是一种适用于结构良好的阵列的方法。如果您无法组织阵列,则应尝试使此方法在原始阵列上递归递归。这导致了很多工作。因此,使用SplHeap和组织良好的阵列可能是更好的解决方案。