fork download
  1. <?php
  2.  
  3. class ArrayHelper
  4. {
  5. public static function getValue($array, $key, $default = null)
  6. {
  7. if (!is_array($array) && !is_object($array)) {
  8. throw new InvalidParamException('Argument passed to getValue() must be an array or object.');
  9. }
  10. if ($key instanceof \Closure) {
  11. return $key($array, $default);
  12. }
  13. if (is_array($key)) {
  14. $lastKey = array_pop($key);
  15. foreach ($key as $keyPart) {
  16. $array = static::getValue($array, $keyPart);
  17. }
  18. $key = $lastKey;
  19. }
  20. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) {
  21. return $array[$key];
  22. }
  23. if (($pos = strrpos($key, '.')) !== false) {
  24. $array = static::getValue($array, substr($key, 0, $pos), $default);
  25. $key = substr($key, $pos + 1);
  26. }
  27. if (is_object($array)) {
  28. // this is expected to fail if the property does not exist, or __get() is not implemented
  29. // it is not reliably possible to check whether a property is accessible beforehand
  30. return $array->$key;
  31. } elseif (is_array($array)) {
  32. return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
  33. } else {
  34. return $default;
  35. }
  36. }
  37. }
  38.  
  39.  
  40. $arrayHelper = new ArrayHelper();
  41.  
  42.  
  43. print_r($arrayHelper::getValue($_POST, 'username'));
  44. echo "\n";
  45.  
  46. $post = ['username' => 'forecho'];
  47. print_r($arrayHelper::getValue($post, 'username'));
  48. echo "\n";
  49.  
  50. class Address
  51. {
  52. public $street = '唐人街';
  53. }
  54.  
  55. class User
  56. {
  57. public $username = 'forecho1';
  58. public $address;
  59.  
  60. function __construct()
  61. {
  62. $this->address = new Address();
  63. }
  64. }
  65.  
  66. print_r($arrayHelper::getValue(new User(), 'username'));
  67. echo "\n";
  68.  
  69.  
  70. print_r($arrayHelper::getValue(new User(), 'address.street'));
  71. echo "\n";
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79. $versions = ['date' => '2016年12月19日', '1.0' => ['date' => '2016年12月18日']];
  80. print_r($arrayHelper::getValue($versions, ['1.0', 'date']));
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
forecho
forecho1
唐人街
2016年12月18日