You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用array_fill_keys和array_walk为数组赋值键名时遇异常求助

Fixing Your Array Merging Issue: Mapping Headers to Data Rows

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:23:28