This function will look for a key in multidimensional arrays, and return the paths to all the results found, or return false if none have been found.
<?php
function array_multi_key_exists($key, $array, $first=true, &$return=array()){
if($first){
while($ret = array_multi_key_exists($key, &$array, false)){
$r[]=$ret;
}
if(empty($r[0])){
return $r[0]=array();
}else{
return $r;
}
}
foreach($array as $k => $v){
if($k === $key && !(is_array($v))){
unset($array[$k]);
array_unshift($return, $k);
return $return;
}elseif($k === $key && is_array($v)){
if(empty($v)){
unset($array[$k]);
}else{
if(array_multi_key_exists($key, &$array[$k], false, $return)){
array_unshift($return, $k);
return $return;
}
}
array_unshift($return, $k);
unset($array[$k]);
return $return;
}else{
if(is_array($v)){
if(array_multi_key_exists($key, &$array[$k], false, $return)){
array_unshift($return, $k);
return $return;
}
}
}
}
return false;
}
?>
The next function takes the array of paths returned by array_multi_key_exists as parameter and returns the corresponding values.
<?php
function array_multi_values($paths, $array){
$return = array();
foreach($paths as $n => $path){
$val = $array;
foreach($path as $dim => $key){
$val = $val[$key];
}
$return[$n] = $val;
unset($val);
}
return $return;
}
?>
This next function takes the paths array returned by array_multi_key_exists, and unsets the corresponding values of the original array, returning the clipped array.
<?php
function array_multi_clip($paths, $array, $key=0, $path=false){
while($path==false){
foreach($paths as $path){
array_multi_clip($paths, &$array, 0, $path);
}
return $array;
}
$n = count($path);
if($key == $n-1){
unset($array[$path[$key]]);
return $array;
}else{
array_multi_clip($paths, &$array[$path[$key]], ++$key, $path);
}
}
?>
Examples:
<?php
$array = array(
'colours' => array(
'red' => array(
'veg' => 'tomato',
'fruit' => 'strawberry',
'green' => 'colourblind',
),
'green' => array(
'green' => 'envy',
'unripe' => 'veggies',
),
'blue' => 'smurfs',
),
);
$key = 'green';
$paths = array_multi_key_exists($key, $array);
print_r($paths);
?>
The result will be an array of paths:
Array
(
[0] => Array
(
[0] => colours
[1] => red
[2] => green
)
[1] => Array
(
[0] => colours
[1] => green
[2] => green
)
[2] => Array
(
[0] => colours
[1] => green
)
)
As it can be seen, if one of the results is an array which again contains the key searched, both will show up in the results.
Example of array_multi_values:
<?php
$values = array_multi_values($paths, $array);
print_r($values);
?>
Result:
<?php
Array
(
[0] => colourblind
[1] => envy
[2] => Array
(
[green] => envy
[unripe] => veggies
)
)
?>
Example of array_multi_clip():
<?php
$clipped = array_multi_clip($paths, $array);
print_r($clipped);
?>
Result:
<?php
Array
(
[colours] => Array
(
[red] => Array
(
[veg] => tomato
[fruit] => strawberry
)
[blue] => smurfs
)
)
?>