如何将php关联数组排序为特定顺序?

这是我喜欢在一个特定的顺序如何将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);

回答:

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

回答:

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

$arrary_sort = ["break", "period1"]; 

$final_array = array_combine($array_sort, $your_array_here);

回答:

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

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

demo

回答:

另外,您可以使用一个实际排序功能:

uksort(

$aData,

function($a,$b)use($arraySort){

return array_search($a, $arraySort) - array_search($b, $arraySort);

}

);

  • http://php.net/manual/en/function.uksort.php
  • http://php.net/manual/en/function.array-search.php

以上是 如何将php关联数组排序为特定顺序? 的全部内容, 来源链接: utcz.com/qa/267056.html

回到顶部