Search code examples
phparray-merge

php - array_combine or array_merge?


I'm sure this is easy for someone well-versed in php, but I've made the mistake of overloading my brain, so now I'm really confused as to whether I should use array_combine, array_merge, or something else... I've been googling and reading php.net for 4 hours and I think I'm just confusing myself even more...

Essentially, I just want to combine an array while keeping the keys?

//Here are the original arrays
[field_sreference] => Array
    (
        [0] => Array
            (
                [nid] => 28
            )

        [1] => Array
            (
                [nid] => 28
            )

        [2] => Array
            (
                [nid] => 29
            )
    )

[field_idelta] => Array
    (
        [0] => Array
            (
                [value] => 0
            )

        [1] => Array
            (
                [value] => 1
            )

        [2] => Array
            (
                [value] => 0
            )
    )

[field_iswitch] => Array
    (
        [0] => Array
            (
                [value] => 0
            )

        [1] => Array
            (
                [value] => 0
            )

        [2] => Array
            (
                [value] => 0
            )
    )

//Here is what I'm trying to achieve:

[combinedarray] => Array
        (
            [0] => Array
                (
                    [nid] => 28
                    [idelta] => 0
                    [iswitch] => 0

                )

            [1] => Array
                (
                    [nid] => 28
                    [idelta] => 1
                    [iswitch] => 0
                )

            [2] => Array
                (
                    [nid] => 29
                    [idelta] => 0
                    [iswitch] => 0
                )
        )

Solution

  • You can solve this is O(n) by simply iterating the arrays...

    $combinedarray = array();
    $len = count($field_sreference);
    for ($i = 0; $i < $len; $i++) {
        $combinedarray[] = array("nid" => $field_sreference[$i]['nid'], 
                                 "idelta" => $filed_idelta[$i]['value'], 
                                 "iswitch" => $field_iswitch[$i]['value']);
    }
    

    This assumes, the 3 arrays are all of equal length.