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
It looks like it could be parsed with parse_str()
, but not without some conversion:
$str = '["Day1"]["Morning"]=mutton&["Day1"]["Evening"]=Juice&["Day2"]["Morning"]=burger&["Day2"]["Evening"]=pizza';
parse_str(preg_replace('/(?<=^|&)/', 'x', str_replace('"', '', $str)), $a);
var_dump($a['x']);
It removes the double quotes, prefixes each entry with x
and then applies parse_str()
. To get an idea of what the preg_replace()
does, the intermediate result is this:
x[Day1][Morning]=mutton&x[Day1][Evening]=Juice&x[Day2][Morning]=burger&x[Day2][Evening]=pizza
Parsing the above string yields an array with a single root element x
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.