CSV 以输出包含具有 JSON 数据的字段的数组

CSV to Output an Array that contains a field with JSON data

使用 Laravel 5.2 并且我想导入 CSV 并将记录存储在数据库中。姓名、姓氏和联系电话将是核心字段,其他任何内容都只是我想在附加信息字段 JSON 中存储的附加数据

示例

* | name | surname | contact_number | gender | race |"
* | piet | pokol   | 0111111111     | male   | race |"

会这样存储:

* ['name'=>'piet','surname'=>'pokol', 'contact_number'=>'0111111111', 'additional_data'=>'{gender:"male", race:"green"}']

我的问题是,是否可以像这样将数组与 JSON 数组组合?

到目前为止,我已经开始使用这段代码制作传统数组

foreach ($reader as $index => $row) {

                if ($index === 0) {
                    $headers = $row;
                } else {


                    $data = array_combine($headers, $row);

                    $array = array_merge($data, ['client_id' => $client_id, 'list_id' => $list_id]);

                    Customer::create($array);

                }

            }

但我需要JSON编码所有不是核心字段的字段,然后将它们添加到数组中。

有人对此有什么建议吗?

检查下面的代码,它可能对你有帮助。您可以使用结果数组存储在数据库中。

<?php
$data = array(
                'name'=> "My Name",
                'surname'=> 'My Surname',
                'contact_number'=> '0987456321',
                'age'=> '38',
                'gender'=> 'female',
                'address'=> 'NewYork, USA',
                );

$core = array('name','surname','contact_number');
$result = array();
$additional = array();

foreach($data as $key => $val) {
    if(in_array($key, $core)) {
        $result[$key] = $val;
    } else {
        $additional[$key]= $val;
    }
}

if(count($additional)) {
    $result['additional'] = json_encode($additional);
}
echo "<pre>";
print_r($result);
?>