1

我有以下代码用于读取 csv 文件

function read_CSV_royal($royal_csv) {
$file_handle = fopen($royal_csv, 'r');
while (!feof($file_handle)) {
$line_of_text[] = fgetcsv($file_handle, 1024, ';');
}
fclose($file_handle);
return $line_of_text;
}
$royal_csv = 'royal.csv';
$csv1 = read_CSV_royal($royal_csv);

输出是:

Array
(
[0] => Array
    (
        [0] => book1
        [1] => description1
        [2] => category1
        [3] => code1
        [4] => editor1
        [5] => 0
        [6] => eur
        [7] => out of stoc
    )

[1] => Array
    (
        [0] => book2
        [1] => description2
        [2] => category2
        [3] => code2
        [4] => editor2
        [5] => 0
        [6] => curr2
        [7] => out of stoc
    )

[2] => Array
    (
        [0] => book3
        [1] => description3
        [2] => category3
        [3] => code3
        [4] => editor3
        [5] => 12
        [6] => curr3
        [7] => in stoc
    )

)

我想根据自己的喜好按值重新排列数组(因为我将要读取的 csv 文件的格式不一样,所以我希望结果数组在未来的分析中完全一样[格式化明智]。我决定使用 foreach 循环重新排列数组,但它没有给我我需要的结果。

function read_CSV_royal($royal_csv) {
$file_handle = fopen($royal_csv, 'r');
while (!feof($file_handle)) {
$line_of_text[] = fgetcsv($file_handle, 1024, ';');
}
fclose($file_handle);
return $line_of_text;
}
$royal_csv = 'royal.csv';
$csv1 = read_CSV_royal($royal_csv);

foreach ($csv1 as $key => &$value) {
 $n_array = array($value[7],$value[6],$value[5],$value[4],$value[3],$value[2],$value[1],$value[0]);
}
echo '<pre>';
print_r ($csv1);
echo '</pre>';

echo '<pre>';
print_r ($n_array);
echo '</pre>';

print_r($csv) 返回正确的结果(具有 3 个数组元素的数组),但 print_r ($n_array); 返回一个只有一个数组的数组)

Array
(
[0] => Array
    (
        [0] => in stoc
        [1] => curr3
        [2] => 12
        [3] => editor3
        [4] => code3
        [5] => category3
        [6] => description3
        [7] => book3
    )

)

我究竟做错了什么?由于我不是程序员,因此将不胜感激任何有关此问题的帮助。

PS:$n_array 的顺序以不作为 adliteram (array_reverse) 为例

4

0 回答 0