我需要这个函数来返回一个数组。当我调用该函数时,它正在打印数组,但是当我在函数中使用return $finalResult
时,它只打印第一个数组。
function readData($file)
{
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach ($textLines as $line)
{
$expLine = explode("\t", $line);
if (count($expLine) < 8)
{
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" => $expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr = $finalResult;
print_r($arr);
}
}
答案 0 :(得分:0)
嗨,您可以合并或推送数组到$ finalResult,请参阅sammple
function readData($file){
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
//Here []
$finalResult[] = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
//$arr=$finalResult;
//print_r($arr);
}
return $finalResult;
}
答案 1 :(得分:-2)
如我在上面的评论中所述
function readData($file){
$arr = array();
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr=array_merge($arr, $finalResult);
}
return $arr;
}