Array get path
With this function you can find values in an array by
an path like "abc/def/ghi".
This function was an idea, I had a few months ago...
function ArrayGetPath($data, $path, &$result){ $found = true; $path = explode("/", $path); for ($x=0; ($x < count($path) and $found); $x++){ $key = $path[$x]; if (isset($data[$key])){ $data = $data[$key]; } else { $found = false; } } $result = $data; return $found; } // Please look at the examples (below)
Snippet Details
-
AuthorJonas John
-
LicensePublic Domain
-
LanguagePHP
-
Created04/27/2006
-
Updated04/27/2006
-
Tagsarray functions
// test data: $tree_data = array( 'red' => array( 'max' => 100, 'min' => 0 ), 'blue' => 'water', 'green' => 'flowers', 'grey' => array( 'light' => array('eeeeee', 'e7e7e7'), 'dark' => array('cccccc') ), 7 => 'foobar' ); // path tests: $path_tests = array( 'red/max', 'foo/bar', 'grey/light/1', 'grey/dark', 'grey/dark/1', 'red/min', 'red/min/1', 'abc/def/ghi', '7', 'grey' ); // loop trough all path tests: for ($x=0; $x < count($path_tests); $x++){ $test_path = $path_tests[$x]; // test path: if(ArrayGetPath($tree_data, $test_path, $result)){ print "The array path '$test_path' was found, showing content:<br/>\n<pre>"; print_r($result); print "</pre>"; } else { print "The array path '$test_path' was not found!<br/>\n"; } print "<br/>\n"; }
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
Satyr March 13, 2011 at 01:37
Exactly, what i looking for. Thanks:)
Peter B. February 15, 2008 at 12:38
Awesome! It's like XPath for arrays!
That's a pretty cool function there.
That's a pretty cool function there.