2

hello I using laravel and magento DB to get data, I want to make tree like structure of following data. Initially when I got data is like this.

Array
(
   [parent] => Array
        (
        [0] => Array
            (
                [entity_id] => 5740
                [name] => Sports
                [parent_id] => 5739
            )

        [1] => Array
            (
                [entity_id] => 6057
                [name] => Football
                [parent_id] => 5740
            )

        [2] => Array
            (
                [entity_id] => 6058
                [name] => American
                [parent_id] => 6057
            )

    )

)

and I want the above data in following format to use in my application.

Array
(
  [parent] => Array
    (
            [0] => Array
            (
                    [entity_id] => 5740
                    [name] => Sports
                    [parent_id] => 5739
                    [child] => Array
                    (
                            [entity_id] => 6057
                            [name] => Football
                            [parent_id] => 5740
                            [child]=> Array
                            (
                                    [entity_id] => 6058
                                    [name] => American
                                    [parent_id] => 6057
                            )
                    )
            )

    )

)

can anyone please help me in this.

1
  • You're probably going to need to post your model relationships and the code your using to actually get the data to get an accurate answer. Commented Apr 11, 2014 at 9:55

1 Answer 1

2

Solution handling unordered hierarchies

function hierarchize($data){
    $parentLess = [];
    $map = [];

    foreach($data['parent'] as &$entity){
        $id = $entity['entity_id'];
        $parentId = $entity['parent_id'];

        $map[$id] = &$entity;

        if(isset($map[$parentId])){
            $map[$parentId]['child'][] = &$entity;
        }else{
            $parentLess[$parentId][] = &$entity;
        }

        if(isset($parentLess[$id])){
            $entity['child'] = &$parentLess[$id];
            unset($parentLess[$id]);
        }
    }

    return $parentLess;
}

https://eval.in/145508

Sign up to request clarification or add additional context in comments.

Comments

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.