如何在csv文件中的一个数组中插入各种值或数组

时间:2021-09-26 13:26:44

I am need to compile a multidimensional array from a .csv file.
My .csv file is:

我需要从.csv文件编译多维数组。我的.csv文件是:

SEC|ID|TITLE|PRICE Section 1
, ID 1, Title 1, 100
, ID 2, Title 2, 100

SEC | ID | TITLE | PRICE第1部分,ID 1,标题1,100,ID 2,标题2,100

I need the array to appear like this:

我需要数组显示如下:

[Section 1] => Array
    (
        [ID 1] => Array
            (
                [Title 1] => 100
            )

        [ID 2] => Array
            (
                [Title 2] => 100
            )

    )

with following sections and subarrays.

以下部分和子阵列。

Currently I have this code:

目前我有这个代码:

$csvArray = array();


if (($handle = fopen("file.csv", "r")) !== FALSE) {

fgetcsv($handle, 1000, ",");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[2] >= "0") {
        $csvArray[][$data[1]] = Array($data[2] => $data[3]);

                }


    elseif ($data[2] < "0") {
        $csvArray[$data[0]] = Array();
            }

    }
fclose($handle);
}
echo '<pre>';
print_r($csvArray);

The output of this is:

这个输出是:

Array
(
[Section 1] => Array
    (
    )

[0] => Array
    (
        [ID 1] => Array
            (
                [Title 1] => 100
            )

    )

[1] => Array
    (
        [ID 2] => Array
            (
                [Title 2] => 100
            )

    )

)

Can anyone help me get an output like I need by changing the csv file or the php? Or is it not possible? Thanks!!

任何人都可以通过更改csv文件或PHP来帮助我获得我需要的输出吗?或者这不可能吗?谢谢!!

1 个解决方案

#1


0  

the numbers as keys is for

作为键的数字是

$csvArray[][$data[1]] = Array($data[2] => $data[3]);

I think that changing to

我认为改变为

$csvArray[$data[0]][$data[1]] = Array($data[2] => $data[3]);

should work (I've not tested it, but the error is quite clear)

应该工作(我没有测试过,但错误很明显)

#1


0  

the numbers as keys is for

作为键的数字是

$csvArray[][$data[1]] = Array($data[2] => $data[3]);

I think that changing to

我认为改变为

$csvArray[$data[0]][$data[1]] = Array($data[2] => $data[3]);

should work (I've not tested it, but the error is quite clear)

应该工作(我没有测试过,但错误很明显)