PHP二维数组处理。把第一个数组的值作为剩下数组的键名

1.csv文件上传,批量添加到数据库中。取到了CSV文件数据到 $arr。需要批量修改键名。求大神帮忙。
Array
(

[0] => Array
    (
        [0] => id
        [1] => pid
        [2] => company
        [3] => department
        [4] => position
        [5] => name
        [6] => tel
        [7] => mobile
        [8] => fax
        [9] => email
        [10] => remark
    )

[1] => Array
    (
        [0] => 10268
        [1] => 139
        [2] => 勘探与生产分公司
        [3] => 营销部
        [4] => 总经理
        [5] => 周杰伦
        [6] => 556666
        [7] => 
        [8] => 
        [9] => 
        [10] => 
    )

[2] => Array
    (
        [0] => 100162
        [1] => 139
        [2] => 勘探与生产分公司
        ...
        
        
        

需要的结果是Array
(

[0] => Array

(
    [id] => 
    [pid] => 
    [company] => 
    [department] => 
    [position] => 
    [name] => 
    [tel] => 
    [mobile] => 
    [fax] => 
    [email] => 
    [remark] => 
)

[1] => Array

(
    [id] => 
    [pid] => 
    [company] => 
    [department] => 
    [position] => 
    [name] => 
    [tel] => 
    [mobile] => 
    [fax] => 
    [email] => 
    [remark] => 
)
阅读 2.8k
2 个回答
$keys = array_shift($data);

$result = array_map(function ($values) use ($keys) {
    return array_combine($keys, $values);
}, $data);
测试一楼的代码 剩下的只有膜拜
$newArray = array();
$csv = array(
        0=>array(
            0=>'id',
            1=>'cid',
            2=>'title'

        ),
        1=>array(
            0=>0,
            1=>0,
            2=>'替换',
        ),
        2=>array(
            0=>1,
            1=>1,
            2=>'测试'
        )
    );
$keys = array_shift($csv);

$result = array_map(function ($values) use ($keys) {
    return array_combine($keys, $values);
}, $csv);
echo '<pre>';
var_dump($result);

$newArray = array();
$csv = array(
        0=>array(
            0=>'id',
            1=>'cid',
            2=>'title'

        ),
        1=>array(
            0=>0,
            1=>0,
            2=>'替换',
        ),
        2=>array(
            0=>1,
            1=>1,
            2=>'测试'
        )
    );
$key = $csv[0];
unset($csv[0]);
foreach ($csv as $kk => $vv) {
    foreach ($vv as $k => $v) {
        $newArray[$kk][$key[$k]] = $v;
    }
    
}
echo '<pre>';
var_dump($newArray);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏