Dss
Dss

Reputation: 2360

convert html input array string into php array?

In PHP, Is there and way or a loop to build an array from a string of varying size?

For example, I want to convert

$str1 = "page[1][name]";
$str2 = "content[1][language][2][name]";

expected output for str1:

$page = array
    1:
       name

expected output for str2:

$content = array
    1:
       language
             2:
                name

But I need it to be the same function that builds the array regardless of how many [] dimensions.

I was thinking something like this:

$tmp = explode("[", $str1);
$arr = (array)$tmp[0];
for ($i=0; $i<count($tmp)-1; $i++) {
    $arr[$i] = array();
        .....
        .....
}

but I'm kinda stuck there and I think it needs to be more of a recursive function method

Upvotes: 1

Views: 1798

Answers (1)

Aleksander Bavdaz
Aleksander Bavdaz

Reputation: 1346

Your input looks much like a query string and if so you can parse it with parse_str().

Example:

$str1 = "page[1][name]";
$str2 = "content[1][language][2][name]";

parse_str($str1, $v);
print_r($v);

parse_str($str2, $v);
print_r($v);

Output is what you expect it to be:

Array
(
    [page] => Array
        (
            [1] => Array
                (
                    [name] =>
                )
        )
)
Array
(
    [content] => Array
        (
            [1] => Array
                (
                    [language] => Array
                        (
                            [2] => Array
                                (
                                    [name] =>
                                )
                        )
                )
        )
)

Upvotes: 4

Related Questions