Aagrlp640
Aagrlp640

Reputation: 70

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.

Upvotes: 0

Views: 79

Answers (5)

Jaimin
Jaimin

Reputation: 872

Its a little long shot, but it works too..

function objectToArray($d) {
    if (is_object($d)) {
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        return array_map(__FUNCTION__, $d);
    }
    else {
        return $d;
    }
}    

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

$text = str_replace("=>",':',$text);
$text = rtrim($text,",");
$text = '{'.$text.'}';

$text = json_decode($text);
$text = objectToArray($text);
print_r($text);

Upvotes: 2

R.K.Saini
R.K.Saini

Reputation: 2708

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

    var_dump($array);

Upvotes: 2

L. Herrera
L. Herrera

Reputation: 490

Combination of str_replace and explode will do the trick. Here it is:

$text ='"list_Menu1"=>"root","list_Submenu1"=>"Menu1","list_Submenu2"=>"Menu1","list_Menu2"=>"root"';
$new_text = explode(",", str_replace("\"","", $text));
$new_arr_ = array();
foreach($new_text as $values) {
    $new_values = explode("=>", $values);
    $new_arr_[$new_values[0]] = $new_values[1];
}

echo '<pre>';
var_dump($new_arr_);
echo '</pre>';

Upvotes: 1

Samay
Samay

Reputation: 471

Hope this helps:-

<?php

function str_to_arr($str) {
  $str = str_replace('"',"",$str);
  $arr = explode(',',$str);
  for($i=0;$i<count($arr);$i++) {
    if($arr[$i]!="") {
      $tmp_arr = explode('=>',$arr[$i]);
      $arr2[$tmp_arr[0]] = $tmp_arr[1];
    }
  }
  return $arr2;
}

$text  ='"list_Menu1"=>"root","list_Submenu1"=>"Menu1","list_Submenu2"=>"Menu1","list_Menu2"=>"root",';
$arr = str_to_arr($text);
print_r($arr);

?>

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

Explode the string by comma (,) and to remove null valued indexes array_filter can be used.

$text ='"list_Menu1"=>"root","list_Submenu1"=>"Menu1","list_Submenu2"=>"Menu1","list_Menu2"=>"root",';
$tree = array_filter( explode(',', $text) );

print '<pre>';
print_r($tree);
print '</pre>';

Upvotes: 1

Related Questions