问题
Have a code that shifts an element of an array up one space.
URL loads:
action?p=ArrayNumber
if (isset($_GET['p'])) {
$index = $_GET['p'];
$panel_dir = 'host.txt';
$panel_data = file($panel_dir);
$pos = $panel_data[$index];
$panel_data[$index] = $panel_data[$index-1];
$panel_data[$index-1] = $pos;
$f_panel = fopen($panel_dir, "w+");
foreach($panel_data as $panel_line) {
fwrite($f_panel, $panel_line);
}
fclose($f_panel);
}
How the content begins:
Array ( [0] => Name [1] => List [2] => Folder [3] => Host )
When print_r($panel_data); the array it shows up correctly:
Array ( [0] => Name [1] => List [2] => Host [3] => Folder )
When echo implode($panel_data); the array combines the moved element:
Name List HostFolder
Bcz of this(?!), it seems to write them combined instead of a new line. It does move it as desire but .. no idea where the combining is coming from.
Name
List
HostFolder
回答1:
Use implode("\n", $array);
to write lines in to you file.
Here is the working example:
$array = [
'Name',
'List',
'Folder',
'Host'
];
$host = $array[3];
$array[3] = $array[3-1];
$array[3-1] = $host;
echo implode("\n", $array);
Result:
Name
List
Host
Folder
来源:https://stackoverflow.com/questions/60462265/php-moving-array-item-shows-correct-array-but-writes-wrong