3
\$\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

2
\$\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\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.