user10253971
user10253971

Reputation: 11

How can I convert a string with square brackets into an array?

I got this from the name attribute of a field

name="field[a][2][b][0][c][1][field_name]"

after serializing the form, I got this:

array('field[a][2][b][0][c][1][field_name]'=>'value')

and I need to convert that into the following array:

$field = array (
         'a' => array (
                [2] => array (
                       'b' => array (
                              [0] => array (
                                     'c' => array (
                                            [1] => array (
                                                 'field_name'=>'value'
                                            )
                                      )
                               )
                        )
                  )
           )
    );

do I need some sort of foreach function or php can recognize this string as array?

Upvotes: 1

Views: 2414

Answers (5)

importantaccount1
importantaccount1

Reputation: 26

Here is your solution: https://codebrace.com/editor/b06588218

I have used regex match twice to match variable name and arrays

/[(.+?)]/ matches any values in the array where "?" is lazy matching. while following regex /^[^[]+/ matches the variable name.

I have used variable variables to create variable from string extracted from above regex

Result:

Array
(
    [a] => Array
        (
            [2] => Array
                (
                    [b] => Array
                        (
                            [0] => Array
                                (
                                    [c] => Array
                                        (
                                            [1] => Array
                                                (
                                                    [field_name] => value
                                                )

                                        )

                                )

                        )

                )

        )

)

I hope this helps

Upvotes: 0

Carsten Massmann
Carsten Massmann

Reputation: 28196

When testing your problem on my PHP server with this test code

<form method="post">
<input type="text" name="field[a][2][b][0][c][1][field_name]">
<input type="submit" value="OK">
<form>
<pre>
<?php
if (isset($_POST['field']))
    print_r($_POST['field']);
?>
</pre>

I got the following response (after entering the word "hello" into the text box and clicking the "OK" button):

Array ( [a] => Array ( [2] => Array ( [b] => 
        Array ( [0] => Array ( [c] => Array ( [1] => 
        Array ( [field_name] => hello ) ) ) ) ) ) ) 

Admittedly, it was formatted nicer, but I am posting from my smartphone, so, please, forgive me for not formatting it again manually.

So, to me it is not quite clear why OP needs extra code to solve his/her problem.

Upvotes: 0

Rei
Rei

Reputation: 6363

If you want the result nested, use parse_str().

$text = "field[a][2][b][0][c][1][field_name]=value";
parse_str($text, $result);
print_r($result);

Output:

Array
(
    [field] => Array
        (
            [a] => Array
                (
                    [2] => Array
                        (
                            [b] => Array
                                (
                                    [0] => Array
                                        (
                                            [c] => Array
                                                (
                                                    [1] => Array
                                                        (
                                                            [field_name] => value
                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)

See https://3v4l.org/7nmFT

Upvotes: 5

Nina Lisitsinskaya
Nina Lisitsinskaya

Reputation: 1818

You can get values in brackets with the regular expression, and then reduce it to the array that you want:

$key = 'field[a][2][b][0][c][1][field_name]';
$value = 'value';

$matches = array();
preg_match_all('/\[([^[]+)\]/', $key, $matches);

$keys = array_reverse($matches[1]);
$result = array_reduce($keys, function ($array, $item) {
    return array($item => $array);
}, $value);

Explanation

In the regular expression \[([^[]+)\]:

  • ([^[]+) is matches any symbol except opening bracket, one or more
    times, and gets it into the capturing group (I hope you will not have nested brackets);
  • \[...\] is literally matches brackets around.

The preg_match_all function should populate the $matches array with following data:

Array
(
    [0] => Array
        (
            [0] => [a]
            [1] => [2]
            [2] => [b]
            [3] => [0]
            [4] => [c]
            [5] => [1]
            [6] => [field_name]
        )

    [1] => Array
        (
            [0] => a
            [1] => 2
            [2] => b
            [3] => 0
            [4] => c
            [5] => 1
            [6] => field_name
        )
)

The $matches[0] have values of a full match and the $matches[1] have values of our first and only capturing group. We have interested only in capturing group values.

Then with the array_reduce function we can simply go through keys in the reverse order, and sequentially wrap our value into an array.

Upvotes: 1

Balaji.J.B
Balaji.J.B

Reputation: 636

You can use explode function to do it. But the values should have space in between them, for example "Hello World" in which the values would be in Array ( [0] => Hello [1] => world ) but in your case it would be like Array ( [0] => field[a][2][b][0][c][1][field_name] ) until $name as space in-between the characters or word.

$name="field[a][2][b][0][c][1][field_name]"
$name_array = explode(" ",$name);
print_r ($name_array);

Upvotes: 0

Related Questions