0

My problem is, I want to combine two arrays, one containing the header of a table, the other the data. I want to create an associative array with column names as keys. Somehow, I get unexpected results (keys are applied to the wrong array) and can't figure out why.

$header = array(array('Name','Position','Salary'));
$data  = array(
    array('John','Manager','30000'),
    array('Cindy','Associate','50000'),
    array('Paul','Staff','20000'),
    array('Mandy','Staff','100000')
    );
array_walk($data, function(&$value, &$key) use ($header) {$value = array_fill_keys($header[0],$value);});
var_dump($data);

Here is the link to an online version: http://sandbox.onlinephpfunctions.com/code/5ad09dbf2c0af5d87f17c64118b9c68a7374a666

What I want to achieve is, that every row from $data has $header[0] as keys.

Regards Christian

1

2 Answers 2

1

You can use array_shift to up index by 1 along with array_combine,

$header = array_shift($header); // to index 1 up    
array_walk($data, function(&$value, &$key) use ($header) {
    $value = array_combine($header,$value);
});
print_r($data);

Demo.

You are using array_fill_keys for the wrong purpose,
here is the demo of its use.

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

Comments

1

use array_combine

array_walk($data, function(&$value, &$key) use ($header) {$value = array_combine($header[0],$value);});

Working example

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.