Code:
$file=file(example);
$arr[]=$file[0];
$arr[] .="interactions. Sage Publications.";
echo count($arr); //outputs 2
echo $arr[0]; //outputs Multiple Regression: Testing and Interpreting
echo $arr[1]; //outputs interactions. Sage Publications
$str=join(" ",$arr);
//outputs
Multiple Regression: Testing and Interpreting
interactions. Sage Publications
问题:虽然我使用连接函数,但输出中没有连接两个数组。我正在两行中获取输出。我想要它在一行中。
替代代码:
$arrp =array("Multiple Regression: Testing and Interpreting","interactions. Sage Publications.");
$str= join(" ",$arrp);
echo $str; //outputs Multiple Regression: Testing and Interpreting interactions. Sage Publications
如果我将数组值直接解析到变量中,则会获得所需的输出(即单行输出(。我以前的代码有什么问题。两个代码不一样吗?
提前谢谢。
原因是您的file(..)
返回一个包含结束换行符的行数组。您的文件实际上看起来像:
lines[0] = "first line'n";
lines[1] = "second line";
.. 这样当你join(..)
它时,字符串有两行。
解决方案#1:
$trimmedLines = file('yourFile', FILE_IGNORE_NEW_LINES);
解决方案#2:
$TrimmedLine = rtrim($arr[1]);
使用 array_merge — 合并一个或多个数组
<?php
$first_array = array('1', '2');
$second_array = array('3', '4');
$final_data = array_merge($first_array, $second_array);
var_dump($final_data);
// output will be
// 1, 2, 3, 4
?>
为什么你为此使用数组。你为什么不直接使用
$file=file(example);
echo trim($file[0]) . "interactions. Sage Publications.";