dpw63348 2014-03-21 17:02
浏览 54
已采纳

为重复的ID键值创建多维数组

I am trying to read in array values from a csv and create sub-arrays which belong to the primary key field ID. E.g currently, say I have the following array structure & content...

ID;number;product

1;K12;product1

2;157/03/2014;product1

2;;product2

2;product1

3;156/03/2014;product2

3;156/03/2014;product3

I have a php function:

function csv_to_array($file, $delimiter=';')
{
    if(!file_exists($file) || !is_readable($file))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($file, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

Such a result would like to achieve

[1] => Array
    (
        [LP] => 1
        [number] => K12
        [product] => product1
    )
[2] => Array
    (
        Array
            (
                [LP] => 2
                [number] => 157/03/2014
                [product] => product1
            )
        Array
            (
                [product] => product2
            )               
        Array
            (
                [product] => product3
            )
  • 写回答

2条回答 默认 最新

  • douchan0523 2014-03-21 17:12
    关注

    Replace

    data[] = array_combine($header, $row);
    

    With

    if(isset($data[$row[0]])) {
    $data[$row[0]][] = array_combine($header, $row);
    }
    else {
    $data[$row[0]] = array();
    $data[$row[0]][] = array_combine($header, $row);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝