0

Hello :) I am a beginner in PHP. I tried several times but did not succeed

I would like to parse a String like : [1,[01,11,12],[20,21,22]] to

`
arr[0][0]=>1
arr[1][0]=>01
arr[1][1]=>11
arr[1][2]=>12
arr[2][0]=>20
arr[2][1]=>21
arr[2][2]=>22
`
Flexxa
  • 25
  • 1
  • 6
  • How many levels of nested arrays can there be? – Nick Nov 03 '19 at 02:19
  • go to php.net and find "eval" function, try to play with that – Anatoliy R Nov 03 '19 at 02:22
  • @Nick It will always be a bidimensionnal array – Flexxa Nov 03 '19 at 02:24
  • [`json_decode()`](https://www.php.net/manual/en/function.json-decode.php) – Sammitch Nov 03 '19 at 03:11
  • @AnatoliyR "If eval() is the answer, you're almost certainly asking the wrong question." Rasmus Lerdorf, PHP Co-Author and BDFL – Sammitch Nov 03 '19 at 03:13
  • @Sammitch agree with the quote, but eval() _is_ the answer for the question whether it's right or wrong. I would not use eval for security reason, but if code complexity is the issue, it's much easier to use eval rather than parse the string and build an array – Anatoliy R Nov 03 '19 at 03:19

1 Answers1

0

You can split your string on a comma that is not enclosed by [ and ] using this regex (inspired by this answer) with preg_split:

,(?![^\[]*\])

and then trim surrounding [ and ] from the resultant parts and split those strings on commas into succeeding elements of the output array. For example:

$string = '[1,[01,11,12] ,4 ,5, [20,21,22]]';
$parts = preg_split('/,(?![^\[]*\])/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$output = array();
foreach ($parts as $part) {
    $part = trim($part, '[] ');
    $output[] = explode(',', $part);
}
print_r($output);

Output:

Array
(
    [0] => Array
        (
            [0] => 1
        )
    [1] => Array
        (
            [0] => 01
            [1] => 11
            [2] => 12
        )
    [2] => Array
        (
            [0] => 4
        )
    [3] => Array
        (
            [0] => 5
        )
    [4] => Array
        (
            [0] => 20
            [1] => 21
            [2] => 22
        )
)

Demo on 3v4l.org

If you're 100% certain of the source and safety of the string, you can also just use eval:

eval("\$output = $string;");

The result will be the same.

Nick
  • 138,499
  • 22
  • 57
  • 95