How do I get an associative array from a string?

This is the starting line: -

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

      

This is my solution, although the "=" at the end of the line does not appear in the array

$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);

      

As a result, I get:

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

      

But I need:

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

      

+3


source to share


3 answers


You can use the prefix parameter preg_split so that it splits the string only once

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

you must change

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

      



to

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

      

Hope it helps

+2


source


$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);

      

This is based on 1) translating using strtr (), preparing the array in json format, and then using json_decode, which brings it into the array well ...



Same result, different approach ...

0


source


You can also use parse_str to parse URL syntax strings for name-value pairs.

Based on your example:

$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);

      

Of course, you need to put some sanity checking in the function, as it might insert some weird stuff into the array like values ​​with empty string keys and whatnot.

0


source







All Articles