Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8406427
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T23:06:26+00:00 2026-06-09T23:06:26+00:00

I have a sample 2d $tasks array which describes a nested structure : Array

  • 0

I have a sample 2d $tasks array which describes a nested structure :

Array
(
    [14] => Array
        (
            [Id] => 14
            [parentId] => null
            [Name] => T1
        )

    [40] => Array
        (
            [Id] => 40
            [parentId] => null
            [Name] => T5
        )

    [41] => Array
        (
            [Id] => 41
            [parentId] => null
            [Name] => T4
        )

    [22] => Array
        (
            [Id] => 22
            [parentId] => 14
            [Name] => T2
        )

    [43] => Array
        (
            [Id] => 43
            [parentId] => 22
            [Name] => T2 child
        )

    [42] => Array
        (
            [Id] => 42
            [parentId] => 14
            [Name] => T3
        )

)

Using the code below I’m transforming this to a proper tree structure :

$sortedArray = array();
// get first level
foreach($tasks as $k => $v){
    if($v['parentId'] == 'null'){
        $sortedArray[$k] = $v;
        unset($tasks[$k]);
    }
}
// sort parents
asort($sortedArray);

function getChildren(array & $a1, array & $a2){
    foreach($a1 as $k => $v){
        findChildren($v, $a2, $k);      
    }
}

function findChildren($rec1, array & $a2, $key){

    foreach($a2 as $k => $v){
        if($rec1['parentId'] == $v['Id']){
            $a2[$k]['children'][$rec1['Id']] = $rec1;
            unset($tasks[$key]);
        } else {
            if (isset($v['children'])){
                findChildren($rec1, $a2[$k]['children'], $key);
            }
        }
    }
}

findChildren($tasks, $sortedArray);

And tho output $sortedArray after running this code looks as follows :

Array
(
    [14] => Array
        (
            [Id] => 14
            [parentId] => null
            [Name] => T1
            [children] => Array
                (
                    [22] => Array
                        (
                            [Id] => 22
                            [parentId] => 14
                            [Name] => T2
                            [children] => Array
                                (
                                    [43] => Array
                                        (
                                            [Id] => 43
                                            [parentId] => 22
                                            [Name] => T2 child
                                        )

                                )

                        )

                    [42] => Array
                        (
                            [Id] => 42
                            [parentId] => 14
                            [Name] => T3
                        )

                )

        )

    [40] => Array
        (
            [Id] => 40
            [parentId] => null
            [Name] => T5
        )

    [41] => Array
        (
            [Id] => 41
            [parentId] => null
            [Name] => T4
        )

)

The problem is, that after calling json_encode on this output array in it’s current state I’m getting :

{"14":{"Id":"14","parentId":"null"...

so all nested arrays are inserted with their indexes. I know I can fix the first level using array_values. But is there any simple way of doing this for all levels ? Without it I end up with ‘children’ being not an array but object which is not satisfying for me.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T23:06:28+00:00Added an answer on June 9, 2026 at 11:06 pm

    The code isn’t present in your post, but $tasks was created as an associative array. In your example you also iterate through $tasks as you would an associative array:

    foreach($tasks as $k => $v){
        ...
    }
    

    You need to add children to $tasks as you would with a numeric array; the difference is this:

    //associative array
    $test = array();
    $test["43"] = "hello";
    $test["40"] = "hello1";
    $test["23"] = "hello2";
    print_r($test);
    
    //numeric array
    $testb = array(); 
    $testb[] = "hello";
    $testb[] = "hello1";
    $testb[] = "hello2";
    print_r($testb);
    

    Live example: http://codepad.org/tsOhX88h

    With the numeric array, the top level index (e.g., 14) you’ve cited as the problem {"14":{"Id":"14","parentId":"null"... is no longer present.

    As a simple final step, use this code to push the items from the associative array on to a new numeric array:

    $finalArray = array();
    foreach ($sortedArray as $key=>$val ){
        $finalArray[] = $sortedArray[$key];
    }
    print_r($finalArray);
    

    Live example: http://codepad.org/uSGSr1DC

    Or you could do it in one shot with array_values:

    $finalArray = array();
    $finalArray = array_values($sortedArray);
    print_r($finalArray);
    

    Live example: http://codepad.org/D7uBSRr8

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a TCP socket connection where I get byte array of data which
I have some simple jQuery code: var response = Array() $('.task-list').each(function() { response.concat(response,$('#' +
I have simple win service, that executes few tasks periodically. How should I pass
I have a simple task to do using PHP dealing with pagination. The idea
I have simple WPF layout task and looking to avoid code-behind if possible. I
I have a simple ZF application (no modules) which works fine when I require
I have a simple form that passes data to backbone, which in turn, submits
I'm new to javascript and have a simple task. I have an array values
I've objects of array, in each object i have different type of strings in
Good day, I have a practical mysql question to which I can't find help

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.