Simon Staton
Simon Staton

Reputation: 4505

php convert a string into multi dimensional array

I have seen many posts on here about converting a multi dimensional array into a string but not the other way around so I have a question to ask. I have got the following string of data which is retrieved from a JQuery array via a post:

["[email protected], [email protected]","http://www.gardengamesltd.co.uk/acatalog/contactus.html"],["[email protected]","http://www.gardengames.com/contact/"],["[email protected]","http://www.gardengamesandleisure.com/ContactUs.aspx"],["[email protected]","http://www.kentgardengameshire.com/contact-us.html"],["[email protected]","http://www.gardengamesuk.com/contact.php"],["[email protected]","http://www.gardenknightgames.com/contact/"],["[email protected]","http://www.just-garden-games.co.uk/"]

What I am wanting to do is convert it into an array which looks like so:

Array
(
    [0] => Array
        (
            [Email] => [email protected], [email protected]
            [FB] => http://www.gardengamesltd.co.uk/acatalog/contactus.html
        )

    [1] => Array
        (
            [Email] => [email protected]
            [FB] => http://www.gardengames.com/contact/
        )
    [2] => Array
        (
            [Email] => [email protected]
            [FB] => http://www.aaeventhire.com/pricing/garden-games
        )

)

I realize I could use $array = explode('","', $harvest_data); however this is only going to give me a single level array and ideally I am wanting to keep email, fb inside an inner array.

Has anyone got any ideas on how I can go about doing this?

Thanks.

Upvotes: 1

Views: 2727

Answers (1)

jeroen
jeroen

Reputation: 91734

As it is, your string is not valid JSON. Wrapping it in a pair of []'s would work in this case so if the input always has this form, this would work:

$json_string = '[' . $your_string . ']';
$your_array = json_decode($json_string);

However, it would be best to make sure that your front-end / javascript posts valid JSON to begin with.

Working example.

Upvotes: 2

Related Questions