Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dot syntax like "this.that.other" to multi-dimensional array in PHP

Tags:

php

parsing

Just as the title implies, I am trying to create a parser and trying to find the optimal solution to convert something from dot namespace into a multidimensional array such that

s1.t1.column.1 = size:33% 

would be the same as

$source['s1']['t1']['column']['1'] = 'size:33%'; 
like image 335
Bryan Potts Avatar asked Mar 09 '12 14:03

Bryan Potts


People also ask

Does PHP have dot notation?

Dot implements PHP's ArrayAccess interface and Dot object can also be used the same way as normal arrays with additional dot notation.

What is array explain multidimensional array in PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

What is multidimensional associative array?

PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.


1 Answers

Try this number...

function assignArrayByPath(&$arr, $path, $value, $separator='.') {     $keys = explode($separator, $path);      foreach ($keys as $key) {         $arr = &$arr[$key];     }      $arr = $value; } 

CodePad

It will loop through the keys (delimited with . by default) to get to the final property, and then do assignment on the value.

If some of the keys aren't present, they're created.

like image 117
alex Avatar answered Sep 19 '22 02:09

alex