Created
July 6, 2015 14:59
-
-
Save zeroasterisk/9a8edfe1df7cb02d1667 to your computer and use it in GitHub Desktop.
[KyOSS Discuss] Help with PHP - using values in indexed array to traverse multi-dimensional array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* pluck out a value from a nested array, based on a $path | |
* where $path is a single-dim list of keys. | |
* | |
* @param array $form (multi-dim) | |
* @param array $path (single dim) | |
* @reutrn mixed $value from $form, in $path | |
*/ | |
function darren($form, $path) { | |
if (!is_array($form)) { | |
throw new OutOfBoundsException("First arg should be an array, within which to look"); | |
} | |
if (!is_array($path)) { | |
throw new OutOfBoundsException("Second arg should be an array, of the path for"); | |
} | |
$ref = &$form; | |
foreach ($path as $key) { | |
if (!in_array($key, $ref)) { | |
throw new OutOfBoundsException("Unable to find {$key}"); | |
} | |
$ref = &$ref[$key]; | |
} | |
return $ref; | |
} | |
// example values to test | |
$form = [ | |
'a1' => [ | |
'b1' => [ | |
'c1' => [ | |
'd1' => 'value' | |
] | |
] | |
] | |
]; | |
$path = ['a1', 'b1', 'c1', 'd1']; | |
$expect = 'value'; | |
echo (darren($form, $path) == $expect ? 'Good' : 'I Hate Life'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment