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

标签 php arrays

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

$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/

相关文章:

php - 为 PHP 查询创建 GridView

php - 如何在使用 fopen 读取文件和填充数组时修复无限循环?

php - laravel 5 csrf_token 值为空

php - 如何使用xPath php获取值(value)

c# - 在 C# 中,如何获取数组内对象的属性?

javascript - 在 Typescript 2 中,如何从对象数组中获取单个属性并分配给新数组?

c# 类对象 - 存储/检索多值列表的最佳方法是什么?

php - Wordpress:建立数据库连接时出错。是的,我已经尝试过了。然后

c - 尝试将程序的执行时间存储到数组中,但数组元素始终显示相同的值

javascript - React-Native 更新 ListView 数据源