使用自定义顺序对关联数组进行排序

时间:2017-07-03 07:10:04

标签: php sorting associative-array

我们如何使用自定义顺序对关联数组进行排序? 我的数组看起来像这样

Array
(
    [pa_color] => Array
        (
            [name] => pa_color
            [value] => 
            [position] => 0
            [is_visible] => 1
            [is_variation] => 1
            [is_taxonomy] => 1
        )

    [pa_dimension] => Array
        (
            [name] => pa_dimension
            [value] => 
            [position] => 1
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-duration] => Array
        (
            [name] => pa_travel-duration
            [value] => 
            [position] => 2
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-type] => Array
        (
            [name] => pa_travel-type
            [value] => 
            [position] => 3
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travelling-with] => Array
        (
            [name] => pa_travelling-with
            [value] => 
            [position] => 4
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_volume] => Array
        (
            [name] => pa_volume
            [value] => 
            [position] => 5
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_weight] => Array
        (
            [name] => pa_weight
            [value] => 
            [position] => 6
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

)

我希望这个数组首先像pa_travel-duration pa_volume秒?我知道有一个原生的php函数usort,但我无法理解这一点。

2 个答案:

答案 0 :(得分:0)

这将完成工作,但我非常确定有更好的方法来做到这一点:

代码:

$array = array("pa_color" => "color",  
              "pa_dimension" => "dimension", 
              "pa_travel-duration" => "Random Stuff: " . rand(100,999),
              "pa_volume" => "volumen"
              );
$tmp = array("pa_travel-duration" =>  $array["pa_travel-duration"],  
            "pa_volume" =>  $array["pa_volume"], 
);

unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);


print_r($array);

结果:

Array
(
    [pa_travel-duration] => Random Stuff: 127
    [pa_volume] => volumen
    [pa_color] => color
    [pa_dimension] => dimension
)

小心,因为如果数组没有正确的键会导致错误,你需要在那里添加一些检查。

答案 1 :(得分:0)

$sort_by = array('pa_travel-duration', 'pa_volume', 'pa_color','pa_dimension','pa_travel-type','pa_travelling-with','pa_weight');
$temp_arr = array();
foreach ($sort_by as $key) {
    $temp_arr[$key] = $data[$key];
}
$data = $temp_arr;

echo '<pre>'; print_r($data);

在$ sort_by数组中定义您的订单