使用array_fill_keys和array_walk为数组赋值键名时遇异常求助
Hey Christian, let's break down why your current code isn't working as expected, and how to fix it quickly.
The Problem with Your Current Code
Your use of array_fill_keys() is the root cause here. This function takes an array of keys and a single value, then assigns that same value to every key in the resulting array. So when you pass $value (which is an entire data row like ['John','Manager','30000']) as the second argument, every header key gets mapped to the full row instead of the corresponding individual value. That's why you're seeing unexpected repeated values under each key.
The Correct Solution: Use array_combine()
What you actually need is array_combine()—this function pairs elements from two arrays: the first array becomes the keys, and the second array becomes the matching values. Exactly what you want to map your headers to each data row.
Here's the revised code:
$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) use ($header) { // Pair header keys with corresponding data values $value = array_combine($header[0], $value); }); var_dump($data);
What This Does
For each row in $data, array_combine($header[0], $value) will create an associative array like this:
[ 'Name' => 'John', 'Position' => 'Manager', 'Salary' => '30000' ]
Which perfectly matches your expected outcome.
A Quick Cleanup Note
You also don't need to pass &$key to your anonymous function since you aren't modifying the keys of the $data array—removing it keeps the code cleaner.
内容的提问来源于stack exchange,提问作者chross

