猿问

CSV 到关联数组(一列作为键,另一列作为值)

我需要将 CSV 文件转换为关联数组,使用一列作为键,另一列作为值。例如,我有这个:


Application,Warehouse,Item,UPC,MFUSA Item No.,"PRODUCT DESCR1","PRODUCT DESCR2",Warehouse ID,Qty

INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100064,8890004,1st STEP B12 LIQUID 16oz,CHERRY CHARGE,11,29

INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100316,8890007,1st STEP B12 LIQUID 16oz,TROPICAL BLAST,11,26

INVENTORY:,Muscle Foods USA,1st STEP B12 LIQUID 16oz,673131100064,8890004,1st STEP B12 LIQUID 16oz,CHERRY CHARGE,12,6

我必须使用该列UPC作为键和Qty值,以便数组看起来像..


array(

    '673131100064' => '29',

    '673131100316 => '26',

    '673131100064' => '6',

);

我已经尝试了在谷歌和这里找到的几种解决方案,但没有一个接近我需要实现的目标。这个问题是类似的,但它是用 Python 编写的。


对不起,我对 PHP 的了解很少。你能指导我走向正确的方向吗?


元芳怎么了
浏览 127回答 3
3回答

白板的微信

使用array_map您可以解析 csv 数据并根据需要使用数组。例子:// Parsing the data in csv file$csv = array_map('str_getcsv', file('path/file.csv'));/*At this point you already have an array with the data but * the first row is the header row in your csv file *///remove header rowarray_shift($csv);$data = [];//Walk the array and add the needed data into some another arrayarray_walk($csv, function($row) use (&$data) {    $data[$row[3]] = $row[8];});就是这样。但是,您作为示例显示的数据具有重复的 UPC。如果您想要一个具有结构的数组,您将覆盖一些数据'UPC' => 'Qty'。数组中不能有重复的键。如果您正在寻找的是获取每个 UPC 的总数量,那么如果 UPC 密钥已经存在,您只需将现有的数量添加到新的数量。// Parsing the data in csv file$csv = array_map('str_getcsv', file('file.csv'));//remove header rowarray_shift($csv);$data = [];//Walk the array and add the needed data into another arrayarray_walk($csv, function($row) use (&$data) {    $data[$row[3]] = ($data[$row[3]] ? $data[$row[3]] + (int) $row[8] : (int) $row[8]);});或者更长但更清晰。//Walk the array and add the needed data into another arrayarray_walk($csv, function($row) use (&$data) {    if(!empty($data[$row[3]]))    {        $data[$row[3]] += (int) $row[8];    }    else {        $data[$row[3]] = (int) $row[8];    }});

侃侃无极

下面代码注释中的解释$array = [];// Open file "$file" and checking that it is not emptyif (($handle = fopen($file, "r")) !== false) {    // loop on each csv line, stopping at end of file    while (($data = fgetcsv($handle)) !== false) {        // Excluding header row & checking data is not empty        if ($data[0] !== 'Application' && !empty($data[0])) {               // fgetcsv returns an array, on your example UPC is on key 3 and Qty on key 9               $array[] = [$data[3] => $data[9]];        }     }     fclose($handle); } return $array;这里的键是硬编码的,但也许你有办法动态地放置它,这取决于你的代码和工作流程。这只是一个简单的(我希望)演示。

翻过高山走不出你

我使用SplfileObject进行阅读。然后第一行用作所有值的键。带有列名的array_column现在可以用于所需的结果。$csv = new SplFileObject('datei.csv');$csv->setFlags(SplFileObject::READ_CSV   | SplFileObject::SKIP_EMPTY   | SplFileObject::READ_AHEAD   | SplFileObject::DROP_NEW_LINE);//Combine first row as key with values$csvArr = [];foreach($csv as $key => $row){  if($key === 0) $firstRow = $row;  else $csvArr[] = array_combine($firstRow,$row);}$arrQty = array_column($csvArr,'Qty','UPC');
随时随地看视频慕课网APP
我要回答