fork download
  1. <?php
  2.  
  3. $array1 = [
  4. 'DIV1' => 'Some element data',
  5. 'SUPPLEMENTAL' => [
  6. 'RPC' => '10.24.122.32',
  7. 'PORT' => '8080'
  8. ],
  9. 'ASG' => 'some arbitrary data'
  10. ];
  11.  
  12. $array2 = [
  13. 'DIV2' => 'Some more element data',
  14. 'ASG' => 'different arbitrary data',
  15. 'DIV1' => 'Some element data that refers to the other object',
  16. 'SUPPLEMENTAL' => [
  17. 'RPC' => '10.24.123.1'
  18. ]
  19. ];
  20.  
  21. function recursiveReKeyArrays(array $array1, array $array2)
  22. {
  23. // Loop through the array for recursion
  24. foreach ($array2 as $key => $value) {
  25. if (!is_array($value)) {
  26. continue;
  27. }
  28.  
  29. $array1[$key] = recursiveReKeyArrays($array1[$key], $value);
  30. }
  31.  
  32. // Find the differences in the keys
  33. foreach (array_diff_key($array2, $array1) as $key => $value) {
  34. $array1[$key] = null;
  35. }
  36.  
  37. return $array1;
  38. }
  39.  
  40. $result1 = recursiveReKeyArrays($array1, $array2);
  41. $result2 = recursiveReKeyArrays($array2, $array1);
  42.  
  43. print_r($result1);
  44. print_r($result2);
Success #stdin #stdout 0.01s 82880KB
stdin
Standard input is empty
stdout
Array
(
    [DIV1] => Some element data
    [SUPPLEMENTAL] => Array
        (
            [RPC] => 10.24.122.32
            [PORT] => 8080
        )

    [ASG] => some arbitrary data
    [DIV2] => 
)
Array
(
    [DIV2] => Some more element data
    [ASG] => different arbitrary data
    [DIV1] => Some element data that refers to the other object
    [SUPPLEMENTAL] => Array
        (
            [RPC] => 10.24.123.1
            [PORT] => 
        )

)