php返回数组中指定列的值或指定索引的赋值

首先会检查输入数组的类型,比如整形、字符串、还是null,如果这三者都不是则为双精度值或是对象
注意:这个输入数组为多维数组
然后经过检测后,循环数组,查找以 c o l u m n k e y 键的值,如果为空,则直接赋给 column_key键的值,如果为空,则直接赋给 columnkey键的值,如果为空,则直接赋给value,如果查找到则将值赋值给 v a l u e 如果参数有 value 如果参数有 value如果参数有index_key键,则以这个 i n d e x k e y 做为键,把 index_key做为键,把 indexkey做为键,把value值赋给这个键

if(!function_exists('array_column'))
{
	
	/*
	*array_column()
	*返回输入数组中指定列的值
	*@param array
	*@param mixed $colnumn_key 	返回 array 中键名为 column_key 的一列值
	*@param mixed $index_key 	使用输入数组中 index_key 列的值将作为返回数组中对应值的键
	*@return array
	*/
	
	function array_column(array $array,$column_key,$index_key=null){
		
		if(!in_array($type=gettype($column_key),array('integer','string','NULL'),TRUE))
		{
			if($type==='double')
			{
				$column_key=(int)$column_key;
			}
			elseif($type==='object' && method_exists($column_key,'__toString'))
			{
				$column_key=(string)$column_key;
			}
			else
			{
				trigger_error('array_column(): The column key 应该是字符串或整数',E_USER_ERROR);
				return false;
			}
		}
		
		if(!in_array($type=gettype($index_key),array('integer','string','NULL'),TRUE))
		{
			if($type==='double')
			{
				$index_key=(int)$index_key;
			}
			elseif($type==='object' && method_exists($index_key,'__toString'))
			{
				$index_key=(string)$index_key;
			}
			else
			{
				trigger_error('array_column(): The index_key 应该是字符串或整数',E_USER_ERROR);
				return false;
			}
		}
		
		$result=array();
		foreach($array as &$a)
		{
			if($column_key===null)
			{
				$value=$a;
			}
			elseif(is_array($a) && array_key_exists($column_key,$a))
			{
				$value=$a[$column_key];
			}
			else
			{
				continue;
			}
			
			if($index_key===null or !array_key_exists($index_key,$a))
			{
				$result[]=$value;
			}
			else
			{
				$result[$a[$index_key]]=$value;
			}
		}
		return $result;
	}
}
//以对象为值的数组
class User{
	public $username;
	public function __construct($name){
		$this->username=$name;
	}
	public function getName(){
		return $this->username;
	}
}

$user=array(
	array('w'=>new User('wang'),'h'=>new User('hang')),
	array('w'=>new User('wan'),'h'=>new User('huang')),
);
$name=array_column($user,'h');
echo $name[0]->getName();

//也可以直接是数组形式
$array=array(
	array('s'=>'sss','h'=>'hhh'),
	array('s'=>'she','h'=>'he'),
);
$data=array_column($array,'s');
print_r($data);
echo $data[0];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值