Best way to convert string to array

I have an array of $AR
I have the line "set[0][p1]"

When defining this string, I need a better way to access the array in $AR['set'][0]['p1']

I have full control over this line, so I don’t need to worry about injections, etc., and I can be sure that it will be well formatted. I cannot put p1 inside ' "set[0]['p1']"

+4
source share
4 answers

Note parse_str() :

 parse_str('set[0][p1]', $AR); 

Oh, you want to access the array index ... Here is my trick:

 getValue($AR, array('set', 0, 'p1')); 

Or if you really should use the original string representation:

 parse_str('set[0][p1]', $keys); getValue($AR, $keys); 

Disclaimer: I have not tested this, you may need array_keys() somewhere.


And helper function:

 function getValue($array, $key, $default = false) { if (is_array($array) === true) { settype($key, 'array'); foreach ($key as $value) { if (array_key_exists($value, $array) === false) { return $default; } $array = $array[$value]; } return $array; } return $default; } 

I would not repeat my path in this problem.

+3
source

My attempt, which is to deal with an arbitrary amount of [] per line:

To break a line, you can use preg_split .

 $parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 

(Details) full code:

 function get_value($string, $array) { $parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); foreach($parts as $part) { $array = $array[$part]; } return $array; } $array = array('set'=>array(array('p1'=>'foo'))); $string = "set[0][p1]"; echo get_value($string, $array); // echoes 'foo' 

I leave you error handling;)

+3
source

This may be crazy, but did you read the statement? It may not be the fastest solution, but it has a novelty in the need for minimal code.

 extract( $AR ); $target = eval("\$set[0]['p1']"); 

The main difference (in terms of input) is that you first need to substitute "$" in the string and make sure that there are quotation marks inside the brackets.

The main advantage is that it becomes extremely obvious what you are trying to execute and you are using two native PHP functions. Both of them mean that the solution will be much more “readable” by those who are not familiar with your system.

Oh, and you use only two lines of code.

+2
source

You need something like. I'm not 100% about the brackets "[" and "]", since I never had to run regex on them before ... if this is wrong, can someone correct me?

 foreach(preg_split('/[\[\]]/', "set[0][p1]") as $aValue) { $AR[$aValue[0]][$aValue[1]][$aValue[2]] = '?'; } 
0
source

Source: https://habr.com/ru/post/1301117/


All Articles