1

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

1 Answer 1

4

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] =>
                                )
                        )
                )
        )
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.