2014-12-22 25 views
-2

代码:加入功能在PHP不工作

$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 

问题:虽然我使用join函数两个数组不能输出连接。我得到两行输出。我想要一条线。

替代代码:

$arrp =array("Multiple Regression: Testing and Interpreting","interactions. Sage Publications."); 
$str= join(" ",$arrp); 
echo $str; //outputs Multiple Regression: Testing and Interpreting interactions. Sage Publications 

如果我直接解析阵列值放入变量我得到所需的输出(ieoutput在单行)。什么是错在我以前的code.Are两代码不一样?

在此先感谢。

回答

1

的原因是你的file(..)返回行的数组,其中包含结束换行符。你的文件实际上是这样的:

lines[0] = "first line\n"; 
lines[1] = "second line"; 

..所以,当你join(..)它,串有两行。


解决方案#1:

$trimmedLines = file('yourFile', FILE_IGNORE_NEW_LINES); 

解决方案2:

$TrimmedLine = rtrim($arr[1]); 
+0

谢谢你的解释和答案。它工作正常。 – vidhya

0

使用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 
?> 
0

为什么你使用数组这个。为什么不干脆用

$file=file(example); 
echo trim($file[0]) . "interactions. Sage Publications."; 
+0

正在使用'file_put_contents'函数将输出写入文件。当我在浏览器中回应它时,我正在获得渴望输出。但是在一个文件中,输出是两行。 – vidhya