mercredi 29 juin 2016

Generic PHP method to compare two nested multidimensional arrays and return the fields whose values are changed or a new field is added

I am having two multidimensional arrays.

NOTE: I am using Laravel 5.1

I am working on developing a generic method, which can compare the two arrays passed to it and return the array elements whose value has changed or a new array element has been added or removed from it.

Suppose I have following two multi dimensional arrays:

Original array:

Array
(
    [id] => 1
    [age] => 27
    [height] => null
    [date_of_joining] => 2012-01-01 00:00:00

    [profile] => Array
    (
        [firstname] => Neelkanth
        [lastname] => Kaushik
    )

    [contact_details] => Array
    (
        ['address'] => Array
        (
            [present_address] => Street-1, XYZ/90
            [permanent_address] => Street-1, XYZ/90
        )
        ['phone'] => Array
        (
            ['office'] => 12344566
            ['home] => 567898765
        )
    )

    [friends] => Array() //Empty array
)

Modified array:

Array
(
    [id] => 1
    [age] => 25 //Changed
    [height] => 150 //changed
    [date_of_joining] => 2016-01-01 00:00:00 //Changed
    [weight] => 120 //New element

    [profile] => Array
    (
        [firstname] => Neelkanth
        //lastname removed
    )

    [contact_details] => Array
    (
        ['address'] => Array
        (
            [present_address] => Street-2, XYZ/90 //Changed
            [permanent_address] => Street-1, XYZ/90
        )
        ['phone'] => Array
        (
            ['office'] => 12344566
            //home removed
        )
    )
    [friends] => Array  //Changed
    (
        [0] => Array //New added
        (
            'friend_id' => 'f1'
        )
        [1] => Array //new added
        (
            'friend_id' => 'f2'
        )
    ) 
)

Final array would be like this:

Array
(
[0] => 'age'
[1] => 'date_of_joining',
[2] => 'weight'
[3] => 'lastname'
[4] => 'present_address',
[5] => 'home',
[6] => 'f1',
[7] => 'f2'
[8] => 'height'
)

I am working on the solution from past few days but can't get my head around this. I am able to make comparison on the outer array using simple loops but having a hard time doing same on the multilevel nested arrays.

Does any one having any idea or a working solution for this.

Please help.

Thanks.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire