4

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 ?

2
  • How are you getting this data? It hardly looks standard. Commented Feb 13, 2014 at 6:36
  • there are large data like this in my client database .. I am trying to clean it Commented Feb 13, 2014 at 6:36

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect like piece of cake :D , can i know what you are doing inside loop ?
Inside the loop the elements are exploded using = and last element is assigned as value. whereas the first element is checked for double quote matches and they are caught up in another array $matches. So those values are subjected as the keys to your new array.
4

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.

2 Comments

+1 for a one-liner !
+1 for simple solution :) but sorry i accepted answer already

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.