user2312198 user2312198 - 1 year ago 57
PHP Question

Convert string containing array elements to array

I have a string that I need to convert to an array.
This is my string that I have in a variable:

$text ='"list_Menu1"=>"root","list_Submenu1"=>"Menu1","list_Submenu2"=>"Menu1","list_Menu2"=>"root",'

And I want to insert it into an array like this:

$tree = array(
"list_Menu1" => "root",
"list_Submenu2" => "list_Menu1",
"list_Submenu3" => "list_Menu1",
"list_Menu2" => "root",);

I tried to generate the array doing this:
$tree = array($text)
, but it doesn't work. How can I do thus, I'm a little lost.

Answer Source

Try this

    $text ='"list_Menu1"=>"root","list_Submenu1"=>"Menu1","list_Submenu2"=>"Menu1","list_Menu2"=>"root",';

    $text = str_replace("=>",":",$text);
    // trim last coma   
    $text = trim($text,",");
    $text = "{".$text."}";
    $array = json_decode($text,true);