W
W
wd-3152020-06-09 09:46:54
PHP
wd-315, 2020-06-09 09:46:54

How to implement recursive getting values ​​of a multidimensional (tree) array?

I implement in one application the function of viewing the report. For employees who do not have subordinates - you can view the report only for yourself, for those who have subordinates - give the choice to view a report on them.
Employees are divided into departments and each department has a leader.

An example of displaying data (in what form the database returns them):

UF_HEAD - ID of the head of the department
ID - ID of the department
PARENT - parent of the department

[0] => Array
(
    [ID] => 1
    [NAME] => Рога и копыта
    [UF_HEAD] => 40
)

[1] => Array
(
    [ID] => 86
    [NAME] => Рога
    [PARENT] => 1
    [UF_HEAD] => 88
)

[2] => Array
(
    [ID] => 72
    [NAME] => Копыта
    [PARENT] => 1
    [UF_HEAD] => 88
)

[3] => Array
(
    [ID] => 55
    [NAME] => Рожки
    [PARENT] => 86
    [UF_HEAD] => 70
)


I will convert it to a multidimensional tree array
[1] => Array
(
    [ID] => 1
    [NAME] => Рога и копыта
    [UF_HEAD] => 40
    [CHILDS] =>
    Array
    (
    [86] => Array
    (
        [ID] => 86
        [NAME] => Рога
        [PARENT] => 1
        [UF_HEAD] => 88
        [CHILDS] => Array
        (
        [55] => Array
        (
            [ID] => 55
            [NAME] => Рожки
            [PARENT] => 86
            [UF_HEAD] => 70
        )
        )
    )

    [72] => Array
    (
        [ID] => 72
        [NAME] => Копыта
        [PARENT] => 1
        [UF_HEAD] => 88
    )
    )
)


And here the main problem begins, which I can’t figure out:
I need to somehow add the [CHILDS_ID] field in each branch, in which there will be an array of IDs of all lower divisions.
Or maybe I'm doing something wrong - the main idea is that at the input I have a user ID (in the UF_HEAD table), and I need to collect all the child IDs where the UF_HEAD of the parent partition matches the user ID.

Roughly speaking, so that a user with ID 40 can view reports for all, and with ID = 88 only for departments with IDs 86 and 55.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-09
@wd-315

function addChildrenIds(&$arr) {
  $ids = [];

  if (is_array($arr)) {
    foreach ($arr as &$n) {
      $n['childrenIds'] = addChildrenIds($n['children']);
      array_push($ids, $n['id'], ...$n['childrenIds']);
    }
  }

  return $ids;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question