2016-11-10 3 views
2

Мне предоставлен список данных, и мне нужно разбить его и переместить в разные текстовые файлы. Я пробовал несколько вещей до сих пор, но, похоже, не смог заставить его работать.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, чтобы быть правильный путь, ресурс дан в C: \ XAMPP \ HTDOCS \ PHPLabs \ EE1600Assignment.php на линии 93

сам документ имеет 25 элементов, которые выглядят следующим образом:

123, billy, bobs 

Любая помощь приветствуется. Спасибо

ответ

0

file_get_contents ожидает путь к файлу, но вы предоставляете обработчик файла. Вероятно, вам нужно вместо этого fgets($fileA).

В качестве альтернативы, если вы хотите прочитать полный файл (это не совсем ясно из вашего кода), вы можете использовать fread($fileA).

+0

Для FiLea и FILEB, все, что я хочу сделать, это записать данные в нее из массива. Думаю, это первый ответ, который вы предложили –

0

В соответствии с documentation, file_get_contents требует пути к файлу, который вы хотите открыть (согласно сообщению об ошибке, которое вы получаете - file_get_contents() expects parameter 1 to be a valid path).

Вы переходящая в $fileA - который вы создали ранее с помощью FOPEN вызова

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

Смежные вопросы