php - Recursively merge two arrays, or replace with latter based on a key -


this should easy answer , i'm being thick, have 2 arrays in php:

$data1 = array(   array(     'qid' => 'q-prof-1-1',     'value' => 10,   ),   array(     'qid' => 'q-prof-2-1',     'value' => 3,   ), ); $data2 = array(   array(     'qid' => 'q-prof-2-1',     'value' => 5,   ),   array(     'qid' => 'q-prof-3-2',     'value' => 1,   ), ); 

and want result in:

$result = array(   array(     'qid' => 'q-prof-1-1',     'value' => 10,   ),   array(     'qid' => 'q-prof-2-1',     'value' => 5,   ),   array(     'qid' => 'q-prof-3-2',     'value' => 1,   ), ); 

... 2 merged- but, if finds qid matches another, replace latter.

i've tried mixture of array_merge(), array_merge_recursive(), $data1 + $data2, $data2 + $data1, array_replace(), array_replace_recursive(), array_diff() etc, etc, every options seems return either 2 or 4 values rather three. , of course i've done fair share of s.o hunting.

any ideas? prefer short , sweet massive iterating function of sort!

thanks in advance :) matt

edit:

i've realised if turn arrays inside $data1 & $data2 key-value pairs of merge , replace functions work, eg:

$data1 = array(   'q-prof-1-1' => array(     'qid' => 'q-prof-1-1',     'value' => 10,   ) // ... etc etc ); 

... i'd still rather not have change original data

is there reason can't use associative array? way can have

$array = array('q-prof-1-1' => 10, 'q-prof-2-1' => 3); $array2 = array('q-prof-2-1' =>  5, 'q-prof-3-2' => 1); 

then loop through $array2, push value on if $array doesn't have key (key_exists() if remember right) or if have key merge them how want?

also, not sure, using associative array make array_merge work correctly (possibly).


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -