PHP 将数组移动到不同的文本文件中


PHP Moving an array into different text files?

我得到了一个数据列表,我需要拆分它并将其移动到不同的文本文件中。到目前为止,我已经尝试了一些方法,但似乎无法使其正常工作。

<?php
/*
*order the file based on surname (col 2)
*create two new text files - class A and B
*split the source text into two equal lists
*format them: ID, firstname, lastname. all words must be first letter caps
*move each list to a new file.
*close files
*/
//This function converts every attribute/variable passed to it into a sentence case
function Uppercase($convert) {
    return ucwords($convert);
}
//This function compares two items to see which one is higher
//src: http://php.net/manual/en/function.usort.php
function cmp($a, $b) {
$compResult = strcmp($a[1], $b[1]);
if ($compResult == 0) {
    return strcmp($a[2], $b[2]);
}else {
    return $compResult;
}
}
//This function gets rid of the whitespace that is not needed
function cut($c) {
    return trim($c, " 'n'r'0");
}
//open file
$myfile = fopen("students.csv", "r");
echo "A";
//initialise the array, giving them 'headers'
$array = array();
echo "B";
//sort through the data, moving it to a multidimentional array and setting the   first letter in each item to uppercase
$i=0;
while(!feof($myfile)){
$line = fgets($myfile);
$pieces = explode(",", $line);
$array[$i][0] = $pieces[0];
$array[$i][1] = cut(Uppercase($pieces[2]));
$array[$i][2] = cut(Uppercase($pieces[1]));
$i++;
}   
echo "C";
//sort the file by the second item in the array
usort($array, "cmp");
echo array_shift($array)."<br>";
echo "D";
//create class files
$fileA = fopen("Class 1.txt", "w");
$fileB = fopen("Class 2.txt", "w");
echo "E";
//get size of array
$arraylength = count($array);
//half the array length(
$half = ceil($arraylength /= 2);
//echo $half;
//echo $arraylength."</br>";
echo "F";
echo "<pre>";
print_r($array);
echo "</br>";
//move the first class into a text file
$k = 0;
foreach ($array as $key){
    echo $key[0];
     if ($k < $half) {
        $current = file_get_contents($fileA);
        $current .= $key;
    }
}
 echo "G";
fclose($fileA);
fclose($fileB);
fclose($myfile);
echo "H";

当它运行时,我得到数组中每个项目重复出现的以下行

警告:file_get_contents(( 期望参数 1 是有效的路径,资源在第 93 行的 C:''xampp''htdocs''PHPLabs''EE1600Assignment.php

文档本身有 25 个项目,如下所示:

123, billy, bobs

任何帮助,不胜感激。谢谢

file_get_contents需要一个文件路径,但您提供的是一个文件处理程序。您可能想要改为fgets($fileA).

或者,如果要读取完整的文件(从代码中并不完全清楚(,可以使用fread($fileA) .

>根据文档,file_get_contents需要您要打开的文件的路径(根据您收到的错误消息 - file_get_contents() expects parameter 1 to be a valid path(。

您正在传入$fileA - 您之前使用 fopen 调用创建的

fopen("Class 1.txt", "w");