S
S
Speakea1y12892019-05-21 19:01:07
PHP
Speakea1y1289, 2019-05-21 19:01:07

How to recurse through an array with categories and get the elements ["id"], ["parent"], ["name"] in each category?

Good evening. I have the following array:
47f3b5bb02.png
Each category ["category"] has attributes ["@attributes"] that have ["id"], ["parent"], ["name"] and so on.
The task is to make a recursion through the entire array and for each category display id, parent and name, and in child categories (with nesting - 1) we do not take into account and do not display the element ["parent"]. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
catrinblaidd, 2019-05-23
@catrinblaidd

You would copy a piece of structure as text, not as a picture. Who wants to understand?
If the structure is like this...

code
multimap($arr);

function multimap($array, $level = 0) {
  $result = [];
  foreach ($array as $key => $data) {
    foreach ($data as $inner) {
      $result[$key] = [
        'id' => $inner['@attributes']['id'],
        'name' => $inner['@attributes']['name']
      ];
      if ($level == 0) {
        $result[$key]['parent'] = $inner['@attributes']['parent'];
      }
      unset($inner['@attributes']);
      $result = \array_merge($result, multimap($inner, $level+1));
    }
  }
  return $result;
}

How do you live with such arrays?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question