note 107223 deleted from function.array-search by levim
| From: | levim@php.net | Date: | Mon, 24 Feb 2014 22:45:41 +0000 |
| Subject: | note 107223 deleted from function.array-search by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-198659@lists.php.net to get a copy of this message | ||
Note Submitter: nsstl
----
Some thing that I wrote from a while, for what ever usefull purpose
This retrieves recursively a value from an array using a path-like notation.
with:
$delimiter path delimiter
$strict if false, the search will allow gaps between path's components
<?php
function path_through_array($path, $array, $delimiter = '.', $strict = false)
{
$path_token = explode($delimiter, $path);
$head = array_shift($path_token);
if (isset($array[$head]) && (0 == count($path_token)))
{
return $array[$head];
}
else if (isset($array[$head]))
{
return path_through_array(implode($delimiter, $path_token), $array[$head], $delimiter, $strict);
}
else if ($strict == true)
{
return false;
}
foreach ($array as $key=>$value)
{
if (is_array($value))
{
$found = path_through_array($path, $value, $delimiter, $strict);
if(false != $found)
{
return $found;
}
}
}
return false;
}
//use:
$array1 = array('path' => array('to' => array('get' =>
array('something' => 'bar')), 'somethingelse'), 'foo'
=> 'anotherthing');
$val1 = path_through_array('path.to.get.something', $array1); //
=> will return : 'bar'
$val2 = path_through_array('path.to.get', $array1);
// => will return : array('something'=>'bar')
$val3 = path_through_array('path/to/get/something', $array1, '/');
// => will return : 'bar'
$val4 = path_through_array('path.to.something', $array1); //
=> will return : 'bar'
$val5 = path_through_array('path.to.something', $array1, '.', true);
// => will return : false