2017-07-03 67 views
2

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

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,但我无法理解这一点。

+0

排序按哪个键或价值? –

+0

我想通过数组键如'[pa_dimension]'第一个现在是第二个和'[pa_color]'第二个是第一个 –

回答

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 
) 

因为如果阵列保重没有正确的键会引发错误,你需要在那里添加一些检查。

+0

如果数组来自数据库呢? –

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阵列