1
\$\begingroup\$

I need to update a multidimensional array by same key paths of a multidimensional array.

I think my code can be better condensed :

//source
$array = [
  "hero" => [
    "name" => "Peter",
    "job" => "Spider Man"
  ],
  "dog" => [
    "age" => 5,
    "toys" => [
      "first" => "bone",
      "second" => "ball"
    ]
  ]
];

//values to update
$toUpdate = [
  "hero" => [
    "name" => "Peter Parker",
    "age" => 26
  ],
  "dog" => [
    "name" => "Rex",
    "toys" => [
      "second" => "frisbee"
    ]
  ]
];

$paths = nested_values($toUpdate);

foreach ($paths as $path => $value) {
  $arr = &$array;
  $parts = explode('/', $path);
  foreach($parts as $key){
    $arr = &$arr[$key];
  }
  $arr = $value;
}

function nested_values ($array, $path="") {
  $output = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $output = array_merge($output, nested_values($value, (!empty($path)) ? $path.$key."/" : $key."/"));
    }
    else $output[$path.$key] = $value;
  }
  return $output;
}

var_dump($array);

/*
(array) [2 elements]
  hero: 
    (array) [3 elements]
      name: (string) "Peter Parker"
      job: (string) "Spider Man"
      age: (integer) 26 
  dog: 
    (array) [3 elements]
      age: (integer) 5 
      toys: 
        (array) [2 elements]
          first: (string) "bone"
          second: (string) "frisbee"
      name: (string) "Rex"
*/
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

...wait a sec, am I sitting a job interview?

Yes, we have a native function for this.

Because your array structure is completely associative, array_replace_recursive() is reliable, concise, and self-documenting.

Code: (Demo)

var_export(array_replace_recursive($array, $toUpdate));
\$\endgroup\$
1
  • \$\begingroup\$ I need to perform my google search ^^ Thanks ! \$\endgroup\$
    – aurepito
    Jun 30, 2021 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.