I
I
Ilya Parshakov2016-04-07 16:21:58
PHP
Ilya Parshakov, 2016-04-07 16:21:58

How to order data from an array (parent-child)?

Hello. I can not think of anything, experience is not enough, please help!
There is an array $cats, like:
[term_id] - sequence number.
[parent] - parent number, if the value is 0, then it is the parent itself.
I want to arrange it in the following way:
Parent
Parent
-child
-child
-child
Parent
...
That is, if the parent has children, display them under the parent.
I do this, but it doesn't work:

$cats = get_terms('categories', $args);
foreach($cats as $cat) {
if($cat->parent == 0) {
echo $cat->name;
}
elseif  ($cat->parent != 0 && $cat->parent = $cat->term_id) {
echo '-'.$cat->name;
}
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MassTek, 2016-04-07
@MassTek

www.inphp.org/arts/doc/8
Write a function like this. Get a convenient output array.

T
ThunderCat, 2016-04-07
@ThunderCat

Recursion to help, it is well described in steps and comments.
in this case, your array must be reshaped as in the example:
We select all the data [...] and form an associative array $cats, the key will be the id of the parent category.

foreach($cats as $cat){
        $newcats[$cat['parent_id']][$cat['id']] =  $cat;
    }
$cats = $newcats;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question