如何重新排序数组PHP?

时间:2015-09-02 12:08:18

标签: php arrays

我有阵列,我需要通过另一个阵列重新排序:

这是我的数组:

Array
(
    [0] => Array
        (
            [name] => Haroldas
            [number] => 444
            [address] => g.
            [city] => eee
            [country] => f
            [lastname] => r
        )

    [1] => Array
        (
            [name] => Lukas
            [number] => 999
            [address] => rrr
            [city] => tttt
            [country] => 3
            [lastname] => r
        )
)

这是另一个带有列号的数组,它向我展示如何订购号码(列顺序可以是另一个):

Array
(
    [lastname] => 4
    [name] => 1
    [number] => 5
    [address] => 3
    [city] => 0
    [country] => 2
) 

我需要这样的结果:

Array
    (
        [0] => Array
            (
                [city] => eee
                [name] => Haroldas
                [country] => f
                [address] => g.
                [lastname] => r
                [number] => 444
            )
    ...
    )

2 个答案:

答案 0 :(得分:1)

这应该做的工作:

<?php

$order = [
    'city'     => 0,
    'name'     => 1,
    'country'  => 2,
    'address'  => 3,
    'lastname' => 4,
    'number'   => 5,
];

$data = [
    [
        'name'     => 'Haroldas',
        'number'   => '444',
        'address'  => 'g.',
        'city'     => 'eee',
        'country'  => 'f',
        'lastname' => 'r',
    ],
    [
        'name'     => 'Lukas',
        'number'   => '999',
        'address'  => 'rrr',
        'city'     => 'ttt',
        'country'  => 3,
        'lastname' => 'r',
    ],
];

foreach ($data as &$entry) {
    uksort($entry, function ($a, $b) use ($order) {
        return strcmp($order[$a], $order[$b]);
    });
}

print_r($data);

输出结果为:

Array
(
    [0] => Array
        (
            [city] => eee
            [name] => Haroldas
            [country] => f
            [address] => g.
            [lastname] => r
            [number] => 444
        )

    [1] => Array
        (
            [city] => ttt
            [name] => Lukas
            [country] => 3
            [address] => rrr
            [lastname] => r
            [number] => 999
        )

)

答案 1 :(得分:0)

如果要重新排序使用foreach,请创建一个新数组。

     $arrReorder = [];
    foreach($yourArr as $key => $val){
        $arrReorder[] = ['city' => $val['city'], 'name' => $val['name'], 'country' => $val['country'], 'address' => $val['address'], 'lastname' => $val['lastname'], 'number' => $val['number']  ];
    }
   print_r($arrReorder);