1

Here is my data returned from a CMS function:

array (
0 =>
stdClass::__set_state(array(
 'term_id' => '31',
 'parent' => '26'
)),
1 =>
stdClass::__set_state(array(
 'term_id' => '3',
 'parent' => '0'
)),
2 =>
stdClass::__set_state(array(
 'term_id' => '32',
 'parent' => '26'
)),
3 =>
stdClass::__set_state(array(
 'term_id' => '33',
 'parent' => '26'
)),
4 =>
stdClass::__set_state(array(
 'term_id' => '34',
 'parent' => '26'
)),
5 =>
stdClass::__set_state(array(
 'term_id' => '26',
 'parent' => '3'
)),

I need to convert the above to the following format:

Array
(
[0] => Array
    (
        3
    )
[1] => Array
    (
        26
    )
[2] => Array
    (
        31
        32
        33
        34
    )
)

So let me explain. Each item in the source is a term. Each term has an ID (term_id) and a parent (parent). If the parent == 0 it doesn't have a parent and is level 0. Any child items of level 0 are level 1 and so on.

What I want to return is an array that holds all the levels and its ID's at that level.

Be aware that this is just sample data and there could be many more levels and any number of ID's on each level.

So using PHP how do I achieve what I'm after?

3 Answers 3

4

Assuming valid structure (no orphans and such), can loop through data and pluck each next level, until no more data left:

$output  = array();
$current = array( 0 );
$index   = 0;

while ( ! empty( $data ) ) {
    $parents        = $current;
    $current        = array();
    $output[$index] = array();

    foreach ( $data as $key => $term ) {
        if ( in_array( $term->parent, $parents ) ) {
            $output[$index][] = $term->term_id;
            $current[]        = $term->term_id;
            unset( $data[$key] );
        }
    }

    $index ++;
}

var_dump( $output );
Sign up to request clarification or add additional context in comments.

Comments

1

Whipped this together real quick, kind of dirty but I think it's what you need.

http://snipt.org/vagU0

Comments

0

I think you need more data. For example objects with parent = 26 are at level 2. How do you now that? You need to have another array where you will have parent_id and its level. Then you can iterate through array and build what you want. If this is multidemnsional array you can use array_walk_recursive

3 Comments

For example objects with parent = 26 are at level 2. How do you now that? by determining on which level ID 26 is first, starting from those that have 0. This is quite sufficient and typical hierarchy data in WordPress. :)
He never mentioned it is Wordpress.
which doesn't really mater, just making the point that data is sufficient, WP is just trivia for context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.