2

I want to merge an array like first element to an object like second element. Is it possible to merge a php object and a php array? If so, How do I merge these?

I have snipped via print_r

First Element (array)

Array
(
    [start_date] => 2014-12-28
)

Second Element (object)

Bannerlookup Object
(
    [_new:CActiveRecord:private] => 
    [_attributes:CActiveRecord:private] => Array
        (
            [id] => 1
            [name] => First Banner
            [description] => My first banner description goes here
            [type] => 1
            [position] => 1
            [price] => 20
            [status] => 1
        )

    [_related:CActiveRecord:private] => Array
        (
        )

    [_c:CActiveRecord:private] => 
    [_pk:CActiveRecord:private] => 1
    [_alias:CActiveRecord:private] => t
    [_errors:CModel:private] => Array
        (
        )

    [_validators:CModel:private] => 
    [_scenario:CModel:private] => update
    [_e:CComponent:private] => 
    [_m:CComponent:private] => 
)

Thanks in advance :)

2 Answers 2

2

First convert the object to array.

$new_array = json_decode(json_encode($your_object), true);

Now merge it with the existing array.

$merged_array = array_merge( $old_array, $new_array) ;

merging will cause the same key override by the second array. See Array Merge Manual

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks buddy for quick reply.It really helped me. :) As YII's model object standard I have done like this $obj_to_array=json_decode(json_encode($model->attributes), true); This may help others.... :). And I am aware about key overriding while array merging. Cheers....
1

wow you can do this with more readeblilty and much easier like

$combination = CMap::mergeArray($my_array, $my_model->attributes);

every model has a function getAttributes() which will give you an array of models attributes, and then you can use that, no NEED of JSONENCODEDECODEing it :D

1 Comment

It sounds really interesting. I APPRECIATE this method for YII users. This is the one what I was searching for. I wasn't aware about CMap of YII. I will try this, When I need this again. Anyway thanks for your great answer... :)

Your Answer

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.