将break行转换为数组

时间:2017-03-08 02:13:52

标签: php arrays

我试图将配置内容转换为数组。

这是我的配置内容:

echo Executing Server Config...
lanmode 0
rcon_password dadasdasdsad
maxplayers 10
port 11494
hostname SA-MP 0.3 Server
gamemode0 grandlarc 1
filterscripts base gl_actions gl_property gl_realtime
announce 0
query 1
weburl www.sa-mp.com
maxnpc 0
onfoot_rate 40
incar_rate 40
weapon_rate 40
stream_distance 300.0
stream_rate 1000

我希望将此转换为这样的数组:

$array['lanmode'] // value is 0
$array['rcon_password'] // value is dadasdasdsad
...

所以我怎么能做到这一点,谢谢大家,对不起我的英语。

1 个答案:

答案 0 :(得分:1)

一种方法是使用explode()两次:一次获取每一行,然后一次获得每个元素。

$config = array();
foreach (explode("\n", $configstring) as $v) {
    $exp = explode(" ", $v);
    $config[$exp[0]] = $exp[1];
}

$configstring是您上面给出的配置(没有第一行)。

$config的输出:

Array
(
    [lanmode] => 0
    [rcon_password] => dadasdasdsad
    [maxplayers] => 10
    [port] => 11494
    [hostname] => SA-MP
    [gamemode0] => grandlarc
    [filterscripts] => base
    [announce] => 0
    [query] => 1
    [weburl] => www.sa-mp.com
    [maxnpc] => 0
    [onfoot_rate] => 40
    [incar_rate] => 40
    [weapon_rate] => 40
    [stream_distance] => 300.0
    [stream_rate] => 1000
)

Live demo

如果你想摆脱第一行,就像你拥有" 执行服务器配置...... "在顶部,你可以在爆炸后只是unset()阵列的第一部分,就像这样

$config = array();
$exploded = explode("\n", $configstring);
unset($exploded[0]);
foreach ($exploded as $v) {
    $exp = explode(" ", $v);
    $config[$exp[0]] = $exp[1];
}

Live demo with removal of first line