Jump to content

Interesting array problem


smartalco

Recommended Posts

First, a couple of set-up arrays to explain the question:

--- Base array ---Array ([some_key] = stuff[another_key] = Array (			[second_level]  = 2nd stuff			[level_key_2] = 7			))--- Input array ---Array ([another_key] = Array (			[level_key_2] = 1			))

Now for the problem. See the '1' in the Input array -> another_key -> level_key_2? I want to add it to the same key hierarchy in the Base array. (So the '7' should become an '8'). I think I could do this with a stupidly complex set of functions, but I'm hoping someone here could lend me a simpler method.

Link to comment
Share on other sites

Not sure if this is the most efficient way but you could use loops and a recursive function.Something like:

function addArrValues($arrBase, $arrInput) {   if (is_array($arrBase) && is_array($arrInput)) {	  foreach ($arrBase as $key => $value) {		 foreach ($arrInput as $keyIn => $valueIn) {			if ($key == $keyIn) {			   $arrBase[$key] = addArrValues($value, $valueIn);			}		 }	  }   } else {	  return $arrBase + $arrInput;   }   return $arrBase;}

I took that just off the top of my head so there's sure to errors in it.Edit: See I knew there would be errors. I just did some quick testing and made changes accordingly to my code above.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...