php - Convert a string to a multidimensional array

729

Solution:

If I understood your question correctly, you're asking to convert the string"test[1][2][3][4][5]" toarray(1 => array(2 => array( 3 => array( 4 => array(5 => array()))));

First of all, people usually use the shortarray() notation, which is just[].

Second, why use strings, when you can just type

$test[1][2][3][4][5] = [];

to get what you want.


If you really want strings, you can do it in several ways, one of which is:

function makeArrayFromString($string, &$name)
{
    $namePosEnd = strpos($string, '['); // name ends when first [ starts
    if (!$namePosEnd) return false; // didn't find [ or doesn't start with name

    $name = substr($string, 0, $namePosEnd);

    $dimensionKeys = [];
    $result = preg_match_all('/\[([0-9]+)\]/', $string, $dimensionKeys); // get keys
    if (!$result) return false; // no matches for dimension keys

    $dimensionKeys = array_reverse($dimensionKeys[1]);
    $multiArray = [];

    foreach ($dimensionKeys as $key)
    {
        $key = (int)$key; // we have string keys, turn them to integers
        $temp = [];
        $temp[$key] = $multiArray;
        $multiArray = $temp;
    }

    return $multiArray;
}

$string = 'test[1][2][3][4][5]';
$name = '';
$multiArray = makeArrayFromString($string, $name);

if ($multiArray === false)
    exit('Error creating the multidimensional array from string.');

$$name = $multiArray; // assign the array to the variable name stored in $name
var_dump($test); // let's check if it worked!

Outputs:

array(1) {
  [1]=>
  array(1) {
    [2]=>
    array(1) {
      [3]=>
      array(1) {
        [4]=>
        array(1) {
          [5]=>
          array(0) {
          }
        }
      }
    }
  }
}

Keep in mind that I didn't add any checks if the $name string satisfies the PHP variable naming rules. So you might get an error if you do something like111onetest[1][2][3][4][5], as variable names in PHP can't start with a number.

People are also looking for solutions to the problem: php - Nextcloud sync large files

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.