2017-12-27 611 views
3

这是我喜欢在一个特定的顺序如何将php关联数组排序为特定顺序?

$aData = Array 
    (
    [break] => Array 
     (
      [Indoor room] => 42 
      [Gym Class] => 19 
     ) 
    [finish] => Array 
     (
      [Indoor room] => 42 
      [Gym Class] => 19 
     ) 

    [lunch] => Array 
     (
      [Indoor room] => 7 
     ) 

    [period1] => Array 
     (
      [Indoor room] => 12 
      [Gym Class] => 22 
     ) 

    [period2] => Array 
     (
      [Gym Class] => 14 
      [Indoor room] => 25 
     ) 

    [period3] => Array 
     (
      [Gym Class] => 21 
      [Indoor room] => 11 
     ) 

    [period4] => Array 
     (
      [Gym Class] => 22 
      [Indoor room] => 20 
     ) 

    [period5] => Array 
     (
      [Gym Class] => 16 
      [Indoor room] => 9 
     ) 

) 

排序的数组,但我喜欢它的顺序是:

break, period1, period2, lunch, period3, period5, period6, finish 

这个我想下面的PHP代码

$arraySort = [ 
    "break", 
    "period1", 
    "period2", 
    "period3", 
    "lunch", 
    "period4", 
    "period5", 
    "period6", 
    "finish" 
]; 

    foreach($aData as $period => $catsScore){ 
    echo 'test '.$period.'<br/>'; 
    $periodItem = [$period]; 
    foreach($arraySort as $cat){ 
     echo 'new: '.$cat.'<br/>'; 
     $periodItem[] = $catsScore; 
    } 
    $output[] = $periodItem; 
    } 


print_r($output); 

回答

2

Easy-只需使用arraySort作为关键字,从原来的阵列得到相应的阵列/值,

<?php 

$arraySort = [ 
    "break", 
    "period1", 
    "period2", 
    "period3", 
    "lunch", 
    "period4", 
    "period5", 
    "period6", 
    "finish" 
]; 

$final_array = []; 

foreach($arraySort as $arraySo){ 
    $final_array[$arraySo] = $aData[$arraySo]; 
} 

print_r($final_array); 

输出: - https://eval.in/926361

+0

感谢活着,这是一个我明白了。你只需使用arraySort作为assoc键并从原始数组中获取相应的数组/值,对吗? – alex

+0

@alex是的。这很容易 –

+0

array_combine更快,看起来更简单,IMO。 – Alex

0

您可以使用array_combine用于此目的:

$arrary_sort = ["break", "period1"]; 
$final_array = array_combine($array_sort, $your_array_here); 
+2

这将只是“重命名”现有的价值观,不正确地重新排序它们 –

+0

您更改了键但不重新排列阵列 – splash58

1

请正确有序阵列和值填充源阵列

$final_array = array_replace(array_fill_keys($arraySort, []), $aData); 

demo