如何从字符串中获取关联数组?

时间:2017-08-02 12:52:53

标签: php arrays

这是初始字符串: -

$final = Get-ChildItem 'C:\' -Include '*.dll' -Recurse | Where-Object {
    $_.FullName -notmatch '^C:\\windows\\(system|temp|winsxs)\\' -and
    $_.FullName -notlike '*\obj\*' -and
    $_.VersionInfo.LegalCopyright.Contains('Microsoft')
}

这是我的解决方案,虽然字符串末尾的“=”没有出现在数组

NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n

这是我得到的结果:

$env = file_get_contents(base_path() . '/.env');

    // Split string on every " " and write into array
    $env = preg_split('/\s+/', $env);

    //create new array to push data in the foreach
    $newArray = array();

    foreach($env as $val){

        // Split string on every "=" and write into array
        $result = preg_split ('/=/', $val);

        if($result[0] && $result[1])
        {
            $newArray[$result[0]] = $result[1];
        }

    }

    print_r($newArray);

但我需要:

Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )

3 个答案:

答案 0 :(得分:2)

您可以使用preg_split的limit参数使其仅拆分字符串

http://php.net/manual/en/function.preg-split.php

你应该改变

$result = preg_split ('/=/', $val);

$result = preg_split ('/=/', $val, 2);

希望这有帮助

答案 1 :(得分:0)

$string    = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate  = [ 'NAME='     => '"NAME":"'      ,
               'LOCATION=' => '","LOCATION":"', 
               'SECRET='   => '","SECRET":"'  ,
               '\n'        => ''               ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array     = json_decode($jsonified, true);

这基于1)使用strtr()进行转换,以json格式准备一个数组,然后使用json_decode将它很好地融入数组...

同样的结果,其他方法......

答案 2 :(得分:0)

您还可以使用parse_str将类似URL语法的字符串解析为名称 - 值对。

根据您的示例:

$newArray = [];

$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);

array_walk(
    $env,
    function ($i) use (&$newArray) {
        if (!$i) { return; }
        $tmp = [];
        parse_str($i, $tmp);
        $newArray[] = $tmp;
    }
);

var_dump($newArray);

当然,你需要对函数进行一些健全性检查,因为它可以在数组中插入一些奇怪的东西,比如带有空字符串键的值,等等。