开发者

Override Array Values with another one

I like to learn how to combine two associative array which has same keys but different values like how we do in jQuery with var options = $.extend(defaults, options);

$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided

$result = combine($first,$second);

//开发者_Python百科output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");

I am looking for something built-in instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.

Thanks...


$result = array_merge($first, $second);

As long as you're dealing with string keys, array_merge does exactly what you want. The two arrays are combined, and where the two have the same keys, the values from $second overwrite the values from $first.


array_merge()


I think array_merge() or array_combine() are the functions you are searching for.


you can iterate on second array and setting each element in first array


I think array_merge() or array_combine() are the functions you are looking for array_merge() may used to merge the two array which are further called. and the array_combine() the keys of a array with the values of a another array.


if you know exactly which key you want override you can simply do that like this $first['name']="jastin"; otherwise you have to use array_merge


I've never found a built-in function for this (simple) need, so I developed a custom function in order to override a $default array with an $override array:

function array_override( $default, $override )
{
    foreach( $default as $k=>$v )
    {
        if( isset( $override[$k] ) ) $default[$k] = $override[$k];
    }
    return $default;
}

As you can see, values in $default are overridden only if are set on the $override array; otherwise the $default value remain on the returned array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜