gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:55:06 24 4
gpt4 key购买 nike

这是我喜欢按特定顺序排序的数组

$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作为assoc key,从原始数组中获取对应的数组/值,

<?php

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

$final_array = [];

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

print_r($final_array);

输出:- https://3v4l.org/4LXvS

关于php - 如何将 php 关联数组排序为特定顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com