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

PHP将数组移动到不同的文本文件中?,php,Php,我得到了一个数据列表,我需要将其拆分并移动到不同的文本文件中。到目前为止,我已经尝试了一些方法,但似乎无法奏效 <?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

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

<?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";

感谢您的帮助。谢谢

文件获取内容
需要一个文件路径,但您提供了一个文件处理程序。您可能需要的是
fgets($fileA)

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

根据,file\u get\u contents需要指向要打开的文件的路径(根据您收到的错误消息-
file\u get\u contents()预期参数1为有效路径

您正在传入
$fileA
——这是您先前使用fopen调用创建的


fopen(“Class 1.txt”,“w”)

对于FileA和FileB,我只想将数据从数组写入其中。我想这是你建议的第一个答案
123, billy, bobs