2

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 ;)

3
  • 1
    please first post your attempts Commented Aug 26, 2021 at 13:42
  • 1
    Are you sure you want Array ( [0] => Array ( [label] => 1 [data] => 2 ) ) instead of Array ([label] => 1 [data] => 2)? Commented Aug 26, 2021 at 13:45
  • you're right. And I have tried: for ($i=0; $i < count($inputs); $i++) { $new = array($cols[$i] => $inputs[$i]); $data[] = $new; } Commented Aug 26, 2021 at 13:48

2 Answers 2

3

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

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

Comments

1

You can do it like so if you want to use a loop

$array1 = ['label', 'data'];
$array2 = [1, 2];

$array_merged = [];

foreach($array1 as $key => $value) {
    $array_merged[$value] = $array2[$key];
}

var_dump($array_merged);

http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.