Answer the question
In order to leave comments, you need to log in
How to convert the string - One.Two.Three into array keys?
Tell me how to convert the string in php:
one.two.three
into
array[one][two][three] = [];
taking into account the fact that there may be Four, or there may be no Three.
Those. I need words separated by a dot to be array keys
. I did this, but it's not correct:
private function _parse_var($string, $vars = []) {
if ( strpos($string, '.') === false ) {
if ( array_key_exists($string, $vars) ) return $vars[$string];
} else {
$string = explode('.', $string);
$string = array_filter($string);
if ( count($string) == 2 ) {
if ( isset($vars[$string[0]][$string[1]]) ) return $vars[$string[0]][$string[1]];
} elseif ( count($string) == 3 ) {
if ( isset($vars[$string[0]][$string[1]][$string[2]]) ) return $vars[$string[0]][$string[1]][$string[2]];
}
}
return false;
}
Answer the question
In order to leave comments, you need to log in
my version
function &ap(&$input, $path = null, $set_value = null)
{
if ( !is_null($path) )
{
if ( !is_array($path) )
{
$path = p2a($path);
}
$node = &$input;
if ( !is_null($set_value) )
{
foreach ( $path as $segment )
{
if ( !isset($node[$segment]) || !is_array($node[$segment]) )
{
$node[$segment] = false;
}
$node = &$node[$segment];
}
$node = $set_value;
return $node;
}
else
{
foreach ( $path as $segment )
{
isset($node[$segment]) || $node[$segment] = null;
$node = &$node[$segment];
}
return $node;
}
}
else
{
return $input;
}
}
function p2a($path, $separator = false)
{
if ( $path === false || $path === '' )
{
return array();
}
else
{
if ( $separator )
$separator = '/' . $separator . '/';
else
$separator = '/';
return explode($separator, $path);
}
}
$link = &ap($array, 'path/to/node');
$link = 123;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question