skip to Main Content

I have two multidimensional arrays.

$options = [
    "type" => "identity",
    "document" => [
        "required" => true,
        "allowed_countries" => null,
        "restricted_countries" => null,
        "allowed_types" => null
    ],
    "send_email" => false
    // .... more options
];

$user_options = [
    "type" => "identity",
    "document" => [
        "required" => false
    ],
    "send_email" => false
];

I would like to merge them into something like this:

 [
          "type" => "identity",
          "document" => [
             "required" => false,
             "allowed_countries" => null,
             "restricted_countries" => null,
             "allowed_types" => null
          ],
          "send_email" => false       
      ];  

When I am trying to merge them, I am not getting the expected results. For example, using array_merge, I get the following.

[
          "type" => "identity",
          "document" => [
             "required" => false,             
          ],
          "send_email" => false       
      ]; 

It removes these keys:

 "allowed_countries" => null,
     "restricted_countries" => null,
     "allowed_types" => null

array_merge_recursive returns the required keys combined in one array:

"document" => array:4 [▼
    "required" => array:2 [▼
      0 => true
      1 => false
    ]    

I also tried collections and the merge method in Laravel, but I didn’t get the expected results and I don’t want that. What can I do?

2

Answers


  1. Can always go the recursive way:

    function mergeArraysRecursive($array1, $array2) {
        foreach ($array2 as $key => $value) {
            if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
                $array1[$key] = mergeArraysRecursive($array1[$key], $value);
            } else {
                $array1[$key] = $value;
            }
        }
        return $array1;
    }
    
    Login or Signup to reply.
  2. You can use the array_replace_recursive() function in PHP.

    $options = [
        "type" => "identity",
        "document" => [
            "required" => true,
            "allowed_countries" => null,
            "restricted_countries" => null,
            "allowed_types" => null
        ],
        "send_email" => false
        // .... more options       
    ];
    
    $user_options = [
        "type" => "identity",
        "document" => [
            "required" => false
        ],
        "send_email" => false       
    ];
    
    $mergedOptions = array_replace_recursive($options, $user_options);
    
    print_r($mergedOptions);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search