Jump to content
  • 0

Форматирование элементов массива


MichaelD
 Share

Question

Всякие вложенные запросы к базе и сложные циклы для меня всегда были проблемой... И тут ещё появилась задача.

Тяну из базы значения таблицы категорий вида:
 

Array   (   [0] => Array   

(   [id] => 7  

[name] => Автомобили

[parent] => 6   )

<!-- тут куча куча элементов -->

)

 

И надо как-то отформатировать данный массив на основе поля parent и id и сделать древовидную структуру.

 

Несколько часов просидел, но мой мозжечок не может понять и реализовать данное задание...

 

 

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Типа такого
 

$tree = [0 => ['id'=>0, 'parent'=>0]];$temp = [0 => &$tree[0]];foreach ($array as $value){      $parent = &$temp[ $value['parent'] ];      if (!isset($parent['children'])) { $parent['children'] = []; }      $parent['children'][$value['id']] = $value;      $temp[$value['id']] = &$parent['children'][$value['id']];}print_r($[0]['children']);
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy