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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度