2
\$\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"
*/
mickmackusa
8,7921 gold badge17 silver badges31 bronze badges
asked Jun 30, 2021 at 7:41
\$\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));
answered Jun 30, 2021 at 13:36
\$\endgroup\$
1
  • \$\begingroup\$ I need to perform my google search ^^ Thanks ! \$\endgroup\$ Commented Jun 30, 2021 at 21:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.