0

I have two nested arrays with different length. I want to make length of second array as per first array, see below examples to get idea. Just remove all those items which don't exist in first array. Sometime second array has more values then first array, in this case my tree structure breaks. These arrays are nested array so simple array_slice not working.

Here are the structure of array.

First Array

 "1": {
    "id": "1",
    "username": "username",
    "children": [
      {
        "id": "-1",
        "username": "NULL",
        "children": [
          {
            "id": "-1",
            "username": "NULL",
            "children": [
              {
                "id": "-1",
                "username": "NULL",
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }

Second Array

"157": {
    "id": "157",
    "username": "test1",
    "children": [
      {
        "id": "158",
        "username": "test1",
        "children": [
          {
            "id": "159",
            "username": "test2",
            "children": [
              {
                "id": "160",
                "username": "test3",
                "children": []
              },
              {
                "id": "160",
                "username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": "160",
        "username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
        "children": [
          {
            "id": "159",,
            "username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",

            "children": [
              {
                "id": "161",
                "username": "KICK ME BECAUSE I M NOT EXIST IN FIRST ARRAY",
                "children": []
              }
            ]
          }
        ]
      }

    ]
  }

Expected Output

"157": {
    "id": "157",
    "username": "test1",
    "children": [
      {
        "id": "158",
        "username": "test1",
        "children": [
          {
            "id": "159",
            "username": "test2",
            "children": [
              {
                "id": "160",
                "username": "test3",
                "children": []
              },

            ]
          }
        ]
      },
    ]
  }

I am trying this method, but it is not working.

        $firstCount = (array_map('count', $actualTree));
        $secondCount = (array_map('count', $emptyTree));
        $chunk =  array_slice($actualTree, 0 , $second[$this->userId], true);

Use Case

The thing which I want to do is that remove those array childrens completely which are not exists in first array. I am building a binary tree upto three levels. First array already has a binary tree with empty values. The second array is data that is coming from the database, and I am simply replacing empty data with the actual data using array_replace. This is working good until second array has more values then first array. So to make it working I have to remove those extra elements.

Could anyone please help me to make there length same. Any help will be appreciated. Thanks in advance.

20
  • First array is invalid. Why do you mean by length of nested array, total number of keys or depth of array? Commented May 9, 2020 at 4:51
  • Hi @Tajniak. I just want to make second array depth same as first. I think I missed structure somewhere. You can take this array as reference. Commented May 9, 2020 at 5:02
  • 1
    Please fix your code and paste sample output you want to achieve. Commented May 9, 2020 at 6:41
  • array_merge() could be a solution? Commented May 9, 2020 at 7:13
  • 1
    This explanation, I feel, is an essential detail for volunteers who may entertain helping you (I am considering helping you) and should be presented in the question body. Commented May 12, 2020 at 7:48

1 Answer 1

2

A Stack Overflow miracle has occurred... I got a recursive snippet to work on the first pass! Usually it takes me a good hour or two to write something that works.

I don't know if I can make it any tighter/better OR if it will fail on any fringe cases, but:

  1. it works for your sample input
  2. it is midnight for me, I'm tired, and I have to work in the morning

Effectively, it synchronously & recursively iterates each array and stores each level of the entry array to the output array so long as the same level keys exists in the structure array.

Code: (Demo)

function truncateRecursive($structure, $entry) {
    $output = [];
    while (($structureKey = key($structure)) !== null && ($entryKey = key($entry)) !== null) {
        $output[$entryKey] = !is_array($entry[$entryKey])
            ? $entry[$entryKey]
            : truncateRecursive($structure[$structureKey], $entry[$entryKey]);
        unset($structure[$structureKey], $entry[$entryKey]);    
    }
    return $output;
}

var_export(truncateRecursive($structure, $entry));

Output:

array (
  157 => 
  array (
    'id' => '157',
    'username' => 'test1',
    'children' => 
    array (
      0 => 
      array (
        'id' => '158',
        'username' => 'test1',
        'children' => 
        array (
          0 => 
          array (
            'id' => '159',
            'username' => 'test2',
            'children' => 
            array (
              0 => 
              array (
                'id' => '160',
                'username' => 'test3',
                'children' => 
                array (
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
)
Sign up to request clarification or add additional context in comments.

3 Comments

really thanks for your help bro. I am too close now. It is giving wrong output for first children. I will see why it is not working in that item. really thanks for your help.
I am swamped at work, but if you give me a 3v4l demo of the sample data that breaks my script, I'll have another look, but it may be a couple days until I am free. Please deliver the sample data in the same instantly usable format as I have done in my demo -- var_export() is your friend.
sure bro. I will try to fix it, but if it stucks, then I will create a sample for you at 3v4l.

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.