phparraysmultidimensional-arraymerging-data

How to merge the children of multiple subarrays


I want to concat all my array contained into one using php,

I have this array at the beginning :

{
  "errors": [
    [
      {
        "id": "login1",
        "error": "Invalid"
      },
      {
        "id": "login2",
        "error": "Invalid"
      },
      {
        "id": "login3",
        "error": "Invalid"
      }
    ],
    [],
    [
      {
        "id": "login10", 
        "error": "Invalid"
      },
      {
        "id": "login11", 
        "error": "Invalid"
      }
    ]
  ]
}

And I want to transform it like this :

{
  "errors": [
      {
        "id": "login1",
        "error": "Invalid"
      },
      {
        "id": "login2",
        "error": "Invalid"
      },
      {
        "id": "login3",
        "error": "Invalid"
      },
      {
        "id": "login10", 
        "error": "Invalid"
      },
      {
        "id": "login11", 
        "error": "Invalid"
      }
  ]
}

I try array_push, array_merge, and array_merge_recursive.

My errors array is populate with multiple arrays of logins, I want to have all in one array. How can I do that?


Solution

  • First off, it appears your have JSON data, so you need to json_decode it.

    Then it appears you need to remove the first level of hierarchy. Loop through the sub-arrays of errors and merge them all together.

    Something like this perhaps:

    $errors = [];
    foreach($array['errors'] AS $subarray) {
        $errors = array_merge_recursive($errors, $subarray);
    }
    

    Working example: https://3v4l.org/JgqgO

    You could also do this with something like array_reduce as well.

    $errors = array_reduce($array['errors'], function($errors, $subarray) {
       return array_merge_recursive($errors, $subarray); 
    }, []);