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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With