Laravel CSV文件读取Angular作为前端

时间:2019-03-07 02:11:24

标签: php laravel csv

大家好!

我在其中有一个CSV文件:

1.453453,4.578413,0.314132,0.764312,0.123422 2.453453,3.578413,0.764312,0.314132,0.123422 3.453453,2.578413,0.123422,0.764312,0.314132 4.453453,1.578413,0.314132,0.123422,0.764312

要用邮递员阅读,这是我的代码:

    $keys = ['PGA', 'PGV', 'X-Axis', 'Y-Axis', 'Z-Axis'];
    $json = [];
    $path = Storage::path('upload/test.txt');
    $file = fopen($path, 'r');
    while (($line = fgetcsv($file)) !== false) {
         $json[] = array_combine($keys, $line);
    }
    fclose($file);
    return json_encode($json);

输出为:

[
    {
        "PGA": "1.453453",
        "PGV": "4.578413",
        "X-Axis": "0.314132",
        "Y-Axis": "0.764312",
        "Z-Axis": "0.123422"
    },
    {
        "PGA": "2.453453",
        "PGV": "3.578413",
        "X-Axis": "0.764312",
        "Y-Axis": "0.314132",
        "Z-Axis": "0.123422"
    },
    {
        "PGA": "3.453453",
        "PGV": "2.578413",
        "X-Axis": "0.123422",
        "Y-Axis": "0.764312",
        "Z-Axis": "0.314132"
    },
    {
        "PGA": "4.453453",
        "PGV": "1.578413",
        "X-Axis": "0.314132",
        "Y-Axis": "0.123422",
        "Z-Axis": "0.764312"
    }
]

但是我需要在数据之前添加'data:'并放在另一个{}中: 像这样:

{    
  "data":  [
        {
            "PGA": "1.453453",
            "PGV": "4.578413",
            "X-Axis": "0.314132",
            "Y-Axis": "0.764312",
            "Z-Axis": "0.123422"
        },
        {
            "PGA": "2.453453",
            "PGV": "3.578413",
            "X-Axis": "0.764312",
            "Y-Axis": "0.314132",
            "Z-Axis": "0.123422"
        },
        {
            "PGA": "3.453453",
            "PGV": "2.578413",
            "X-Axis": "0.123422",
            "Y-Axis": "0.764312",
            "Z-Axis": "0.314132"
        },
        {
            "PGA": "4.453453",
            "PGV": "1.578413",
            "X-Axis": "0.314132",
            "Y-Axis": "0.123422",
            "Z-Axis": "0.764312"
        }
    ]
}

我正在使用angular作为前端,我需要显示它。所以我需要添加上述内容。感谢您提供的每一个帮助!我必须将“ data:”放入网页中。

谢谢!

1 个答案:

答案 0 :(得分:2)

    $keys = ['PGA', 'PGV', 'X-Axis', 'Y-Axis', 'Z-Axis'];
    $json = [];
    $path = Storage::path('upload/test.txt');

    $file = fopen($path, 'r');
    while (($line = fgetcsv($file)) !== false) {
        $json[] = array_combine($keys, $line);
    }
    fclose($file);

    $modified = ["data" => $json];

    return json_encode($modified);