phparraysmultidimensional-arraymerging-data

Synchronously merge column values from the rows of multiple 2d arrays


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?

$field_sreference = [
    ['nid' => 28],
    ['nid' => 28],
    ['nid' => 29]
];

$field_idelta = [
    ['value' => 0],
    ['value' => 1],
    ['value' => 0]
];

$field_iswitch = [
    ['value' => 0],
    ['value' => 0],
    ['value' => 0]
];

Here is what I'm trying to achieve:

[
    ['nid' => 28, 'idelta' => 0, 'iswitch' => 0],
    ['nid' => 28, 'idelta' => 1, 'iswitch' => 0],
    ['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.