PHP Moving Array Item Shows Correct Array but Writes Wrong?

随声附和 提交于 2020-03-25 18:36:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!