Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.