Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string into array in php

I have string like below

["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza 

Which i am trying to convert into array like below

$arr["Day1"]["Morning"] = "mutton";
$arr["Day1"]["Evening"] = "Juice";
$arr["Day2"]["morning"] = "burger";
$arr["Day2"]["evening"] = "pizza";

I tried something like below.

$str = '["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza';
$pieces = explode("&", $str);

foreach($pieces as $pie)
{
$arr.$pie;
}
var_dump($arr);

I know above code is really dumb :/ .Is there any proper solution for this ?

like image 834
Vishnu Avatar asked Jan 11 '23 05:01

Vishnu


1 Answers

You could do like this...

<?php
$str='["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza';
$arr = explode('&',$str);
foreach($arr as $v)
{
    $valarr=explode('=',$v);
    preg_match_all('/"(.*?)"/', $valarr[0], $matches);
    $narr[$matches[1][0]][$matches[1][1]]=$valarr[1];
}

print_r($narr);

OUTPUT :

Array
(
    [Day1] => Array
        (
            [Morning] => mutton
            [Evening] => Juice
        )

    [Day2] => Array
        (
            [Morning] => burger
            [Evening] => pizza
        )

)

You could access like echo $arr["Day1"]["Morning"] which prints mutton

Demo

like image 115
Shankar Narayana Damodaran Avatar answered Jan 16 '23 22:01

Shankar Narayana Damodaran