【问题标题】:Flatten an array of staff members扁平化一系列工作人员
【发布时间】:2020-04-06 08:46:19
【问题描述】:

我有一个工作人员数组,如下所示:

array:22 [▼
  "id" => "58"
  "userID" => "5"
  "title" => "HR Manager"
  "department" => "Human Resources"
  "employed" => "2010-05-11"
  "unemployed" => "0000-00-00"
  "active" => "1"
  "ts" => "2019-03-03 14:49:47"
  "name" => "James Smith"
  "email" => "james.smith@gmail.com"
  "staff" => array:7 [▼
    0 => array:22 [▼
      "id" => "45"
      "userID" => "5"
      "title" => "HR Administrator"
      "department" => ""
      "employed" => "2010-05-11"
      "unemployed" => "0000-00-00"
      "active" => "1"
      "ts" => "2019-03-03 14:49:47"
      "name" => "Jane Smith"
      "email" => "jane.smith@gmail.com"
      "staff" => array:2 [▶]
    ]
    1 => array:22 [▶]
    2 => array:22 [▶]
    3 => array:22 [▶]
    4 => array:22 [▶]
    5 => array:22 [▶]
    6 => array:22 [▶]
  ]
]

因此,每个员工都可以让他们下属的员工向他们报告,并且可以永远持续下去。所以我想要制作的是这个数组的平面版本,它看起来像下面这样:

array:22 [▼
  0 =>  array:10 [
     "id" => "58"
    "userID" => "5"
    "title" => "HR Manager"
    "department" => "Human Resources"
    "employed" => "2010-05-11"
    "unemployed" => "0000-00-00"
    "active" => "1"
    "ts" => "2019-03-03 14:49:47"
    "name" => "James Smith"
    "email" => "james.smith@gmail.com"
    ]
  1 => array:10 [▼
      "id" => "45"
      "userID" => "5"
      "title" => "HR Administrator"
      "department" => ""
      "employed" => "2010-05-11"
      "unemployed" => "0000-00-00"
      "active" => "1"
      "ts" => "2019-03-03 14:49:47"
      "name" => "Jane Smith"
      "email" => "jane.smith@gmail.com"
  ]
]

问题是我知道如何以递归方式从数据库中获取数据,但我不知道如何将这些数据展平为类似于上面的数组。

【问题讨论】:

  • 您的样本结果也不平坦,Jane Smith 有一个人员数组...
  • @Nick 抱歉,我不小心把它丢了,我已经更新了问题。

标签: php arrays recursion


【解决方案1】:

使用递归函数从人员获取人员:

function getStaff($personData, &$staffData) {
    if (isset($personData['staff'])) {
        $personStaffData = $personData['staff'];

        unset($personData['staff']);

        foreach ($personStaffData as $innerPersonData) {
            getStaff($innerPersonData, $staffData);
        }
    }

    $staffData[] = $personData;
}

$staffFlatData = [];

foreach ($personsDB as $person) {
    getStaff($person, $staffData);
}

【讨论】:

  • 谢谢,我没有完全使用你的代码,但是有引用变量让我走到了最后!
猜你喜欢
  • 2019-04-23
  • 1970-01-01
  • 2014-10-29
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2010-12-13
  • 1970-01-01
相关资源
最近更新 更多