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

时间:2016-11-10 13:17:17

标签: 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 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

感谢任何帮助。谢谢

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

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