Answer the question
In order to leave comments, you need to log in
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
www.inphp.org/arts/doc/8
Write a function like this. Get a convenient output array.
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 questionAsk a Question
731 491 924 answers to any question