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 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题