Search code examples
phparraysmultidimensional-arraymergearray-merge

Create multidimensional array from multiple arrays in PHP


I have two arrays:

Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )

And I need merge them in a array like this:

Array ( [0] => Array ( [label] => 1 [data] => 2  ) )

I have tried:

for ($i=0; $i < count($inputs); $i++) {
    $new = array($cols[$i] => $inputs[$i]);
    $data[] = $new;
}

Any help is welcome ;)


Solution

  • You can simply use array_combine:

    Creates an array by using one array for keys and another for its values

    $arr1 = array(0 => 'label', 1 => 'data');
    $arr2 = array(0 => 1, 1 => 2);
    $arr3 = array_combine($arr1, $arr2);
    
    print_r($arr3);
    

    Result:

    Array
    (
        [label] => 1
        [data] => 2
    )
    

    Try it