How to access and manipulate multi-dimensional array by key names / path?
Assuming $path
is already an array via explode
(or add to the function), then you can use references. You need to add in some error checking in case of invalid $path
etc. (think isset
):
$key = 'b.x.z';
$path = explode('.', $key);
Getter
function get($path, $array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$value = get($path, $arr); //returns NULL if the path doesn't exist
Setter / Creator
This combination will set a value in an existing array or create the array if you pass one that has not yet been defined. Make sure to define $array
to be passed by reference &$array
:
function set($path, &$array=array(), $value=null) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($path, $arr);
//or
set($path, $arr, 'some value');
Unsetter
This will unset
the final key in the path:
function unsetter($path, &$array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
if(!is_array($temp[$key])) {
unset($temp[$key]);
} else {
$temp =& $temp[$key];
}
}
}
unsetter($path, $arr);
*The original answer had some limited functions that I will leave in case they are of use to someone:
Setter
Make sure to define $array
to be passed by reference &$array
:
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($arr, $path, 'some value');
Or if you want to return the updated array (because I'm bored):
function set($array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
return $array;
}
$arr = set($arr, $path, 'some value');
Creator
If you wan't to create the array and optionally set the value:
function create($path, $value=null) {
//$path = explode('.', $path); //if needed
foreach(array_reverse($path) as $key) {
$value = array($key => $value);
}
return $value;
}
$arr = create($path);
//or
$arr = create($path, 'some value');
For Fun
Constructs and evaluates something like $array['b']['x']['z']
given a string b.x.z
:
function get($array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");
return $result;
}
Sets something like $array['b']['x']['z'] = 'some value';
:
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$array{$path} = $value;");
}
Unsets something like $array['b']['x']['z']
:
function unsetter(&$array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}
I have solution for you not in the pure PHP, but using ouzo goodies concretely Arrays::getNestedValue method:
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b.x.z';
$path = explode('.', $key);
print_r(Arrays::getNestedValue($arr, $path));
Similarly if you need to set nested value you can use Arrays::setNestedValue method.
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
Arrays::setNestedValue($arr, array('d', 'e', 'f'), 'value');
print_r($arr);
I have a utility I regularly use that I'll share. The difference being it uses array access notation (e.g. b[x][z]
) instead of dot notation (e.g. b.x.z
). With the documentation and code it is fairly self-explanatory.
<?php
class Utils {
/**
* Gets the value from input based on path.
* Handles objects, arrays and scalars. Nesting can be mixed.
* E.g.: $input->a->b->c = 'val' or $input['a']['b']['c'] = 'val' will
* return "val" with path "a[b][c]".
* @see Utils::arrayParsePath
* @param mixed $input
* @param string $path
* @param mixed $default Optional default value to return on failure (null)
* @return NULL|mixed NULL on failure, or the value on success (which may also be NULL)
*/
public static function getValueByPath($input,$path,$default=null) {
if ( !(isset($input) && (static::isIterable($input) || is_scalar($input))) ) {
return $default; // null already or we can't deal with this, return early
}
$pathArray = static::arrayParsePath($path);
$last = &$input;
foreach ( $pathArray as $key ) {
if ( is_object($last) && property_exists($last,$key) ) {
$last = &$last->$key;
} else if ( (is_scalar($last) || is_array($last)) && isset($last[$key]) ) {
$last = &$last[$key];
} else {
return $default;
}
}
return $last;
}
/**
* Parses an array path like a[b][c] into a lookup array like array('a','b','c')
* @param string $path
* @return array
*/
public static function arrayParsePath($path) {
preg_match_all('/\\[([^[]*)]/',$path,$matches);
if ( isset($matches[1]) ) {
$matches = $matches[1];
} else {
$matches = array();
}
preg_match('/^([^[]+)/',$path,$name);
if ( isset($name[1]) ) {
array_unshift($matches,$name[1]);
} else {
$matches = array();
}
return $matches;
}
/**
* Check if a value/object/something is iterable/traversable,
* e.g. can it be run through a foreach?
* Tests for a scalar array (is_array), an instance of Traversable, and
* and instance of stdClass
* @param mixed $value
* @return boolean
*/
public static function isIterable($value) {
return is_array($value) || $value instanceof Traversable || $value instanceof stdClass;
}
}
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b[x][z]';
var_dump(Utils::getValueByPath($arr,$key)); // int 5
?>
As a "getter", I've used this in the past:
$array = array('data' => array('one' => 'first', 'two' => 'second'));
$key = 'data.one';
function find($key, $array) {
$parts = explode('.', $key);
foreach ($parts as $part) {
$array = $array[$part];
}
return $array;
}
$result = find($key, $array);
var_dump($result);