doufei3561 2018-06-19 04:08
浏览 28
已采纳

PHP - 根据CSV中的第一个值创建一个数组

I have a csv like this.

enter image description here

I have created a CLI script, which will read the CSV and It will create an array based on account id, address id and SKU.

I will execute the script like this


    php csvimport.php 10 /var/www/test/testcsv.csv

In the above code, 10 is the limit of the script which will take the first 10 then it will create an array, then it will look for next 10 and it will create another array. Here I need to handle a condition that the first row value of the batch should match the next 9 rows. If there is no match after the first row then will create that row as separate array.

I need the expected output. Every time it will take the limit and compare the rows based on the first row of the limit.

array[A1][ad1] => SKU1,SKU2,SKU3,SKU4,SKU5,SKU25,SKU26
array[A1][ad12] => SKU1
array[A1][ad2] =>  SKU3,SKU4,SKU5,SKU6,SKU7,SKU8
array[A2][ad2-1] =>  SKU13,SKU14,SKU15,SKU16,SKU17,SKU18

$file = '/var/www/html/var/csv/cv1.csv';
$arr=array();
$row = 1;
$i = 1;
$limit = 10;
if (($handle = fopen($file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c = 0; $c < $num; $c++) {
            $arr[$row][$data[0]][$data[1]]= $data[$c];
            if ($i++ == $limit) break;
        }
    }
    fclose($handle);
}

echo "<pre>";
print_r($arr);
exit;
  • 写回答

1条回答 默认 最新

  • doyhq66282 2018-06-19 06:43
    关注

    There is need to update code inside for loop. Update it as:

    for ($c = 0; $c < $num; $c++) {
        if (isset($arr[$data[0]]) && isset($arr[$data[0]][$data[1]])) {
            $arr[$data[0]][$data[1]] .= "," . $data[$num - 1];
        } else {
            $arr[$data[0]][$data[1]] = $data[$num - 1];
        }
        if ($i++ == $limit)
            break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?