Last active
August 29, 2015 14:13
-
-
Save Langmans/59c25f8595fb9085c8aa to your computer and use it in GitHub Desktop.
get array value by point sperated index
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 | |
function get_var($pointed, $arr, $default = '') | |
{ | |
$points = explode('.', $pointed); | |
$var = $arr; | |
$var_name = ''; | |
while (count($points)) { | |
$point = array_shift($points); | |
$var_name .= '.' . $point; | |
// var_dump('-----------------', $point, $var); | |
if (!array_key_exists($point, $var)) { | |
if(func_num_args() == 3){ | |
return $default; | |
} | |
else { | |
throw new \InvalidArgumentException(trim($var_name, '.') . ' not found.'); | |
} | |
} | |
$var = $var[$point]; | |
} | |
return $var; | |
} | |
var_dump( | |
get_var( | |
'videos.0.resource.url.location', | |
array( | |
'videos' => array( | |
array( | |
'resource' => array( | |
'url' => array( | |
'location' => 'http://dragonmediagroup.nl' | |
) | |
) | |
) | |
) | |
) | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment