首先会检查输入数组的类型,比如整形、字符串、还是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];