Skip to content

Instantly share code, notes, and snippets.

@asika32764
Last active December 17, 2015 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asika32764/5625619 to your computer and use it in GitHub Desktop.
Save asika32764/5625619 to your computer and use it in GitHub Desktop.
<?php
class XXXHelperArray
{
/**
* Set a value into array or object.
*
* @param mixed $array An array to set value.
* @param string $key Array key to store this value.
* @param mixed $value Value which to set into array or object.
*
* @return mixed Result array or object.
*/
public static function setValue(&$array, $key, $value)
{
if( is_array($array) ) {
return $array[$key] = $value ;
}elseif( is_object($array) ){
return $array->$key = $value;
}else{
return $array ;
}
}
/**
* A function like JArrayHelper::getValue(), but support object.
*
* @param mixed $array An array or object to getValue.
* @param string $key Array key to get value.
* @param mixed $default Default value if key not exists.
*
* @return mixed The value.
*/
public static function getValue(&$array, $key, $default = null)
{
if( is_array($array) ) {
return JArrayHelper::getValue( $array, $key, $default );
}
// if not Array, we do not detect it for warning not Object
$result = null ;
if( isset($array->$key) ) {
$result = $array->$key ;
}
if(is_null($result)){
$result = $default ;
}
return $result ;
}
}
// 使用方式
// 放在 helpers/array.php 內
$value = XXXHelper::_('array.getValue', $array, 'key', 'default') ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment