获取二维数组里面指定字段的数据,结果返回一维数组
从数据库获取多个数据时往往是二维数组,但是有时候我们需要获取数组里面的某一键的数据。有两种方法:foreach()循环和Array()函数
示例数组,获取二维数组里面的device_token的值并且放在一维数组里面:
$arr = array(
0 => array(
'device_token' => 'AnBWyVMD1u0qKkNrD44h8BaFjROX5qCRgDjEG6CCFtFd',
'shebei' => 'android'
),
1 => array(
'device_token' => 'Ap0pTms6pvxMtsvrqCvzbqknLkO6KEIJnk3x9iGYlgd8',
'shebei' => 'android'
),
2 => array(
'device_token' => '6aa7d1356e75a56758a0fdc40b776d0cab7fa8889de546106888d3b3c5eee872',
'shebei' => 'ios'
),
3 => array(
'device_token' => '9e9854b6b6f02c58aa8838619b25e18139558dca9f69e2abbc6f9b88630ff269',
'shebei' => 'ios'
),
4 => array(
'device_token' => 'ApKqVYFWWXNds9CnveE24ysTZ942nw5P2o5lE6KJegqg',
'shebei' => 'android'
),
5 => array(
'device_token' => '',
'shebei' => 'ios'
),
6 => array(
'device_token' => 0,
'shebei' => 'android'
)
);
一、foreach()循环
$IOS_token = array();
$android_token = array();
if(!empty($arr) && count($res) != 0){
foreach($arr as $key => $val){
if($val['shebei'] == 'android'){
$android_token[] = $val['device_token'];
}elseif($val['shebei'] == 'ios'){
$IOS_token[] = $val['device_token'];
}
}
}
二、Array()函数
$ios_res = array_column(array_filter($arr,function($val){
if($val['shebei'] == 'ios'){
return $val['device_token'];
}else{
return false;
}
}),'device_token');
$android_res = array_column(array_filter($arr,function($value){
if($value['shebei'] == 'android'){
return $value['device_token'];
}else{
return false;
}
}),'device_token');
返回结果一维数组:
Array ( [ios] => Array ( [0] => 6aa7d1356e75a56758a0fdc40b776d0cab7fa8889de546106888d3b3c5eee872 [1] => 9e9854b6b6f02c58aa8838619b25e18139558dca9f69e2abbc6f9b88630ff269 ) [android] => Array ( [0] => AnBWyVMD1u0qKkNrD44h8BaFjROX5qCRgDjEG6CCFtFd [1] => Ap0pTms6pvxMtsvrqCvzbqknLkO6KEIJnk3x9iGYlgd8 [2] => ApKqVYFWWXNds9CnveE24ysTZ942nw5P2o5lE6KJegqg ) )
原始数组$arr中ios其实有三个,但是有一个是空值,所以array_filter()函数给过滤掉了;android分类下的0也被过滤掉了。
注意点:array_filter会过滤掉任何值等于FALSE的值,也就是说 0值,空字符串,null,都会被过滤