/**
* 取多维数据中某字段的值
* @param array $array 数据源数组
* @param string|array $field 要获取的字段
* @return array 结果数组
*/
function array_muliti_field($array, $field)
{
$resp = [];
foreach($array as $k => $v) {
if(is_array($field)) {
foreach($field as $f) {
if(isset($v[$f]) && $v[$f] !== null) {
$resp[$f][$v[$f]] = $v[$f];
}
}
} elseif(isset($v[$field]) && $v[$field] !== null){
$resp[] = $v[$field];
}
}
return $resp;
}/**
* 将多维数组中的某一个元素作为键名,重新生成数组
*
* $array = [
* 0 => ['id'=>10, 'title'=>'t10'],
* 1 => ['id'=>11, 'title'=>'t11']
* ];
*
* $res = array_set_key($array, 'id');
*
* 结果如下:
* $res = [
* 10 => ['id'=>10, 'title'=>'t10'],
* 11 => ['id'=>11, 'title'=>'t11']
* ];
*
* @param array $array 要处理的数组
* @param string $key 作为 key 的字段名称
* @param string $valuekey [description]
* @return array 新生成的数组
*/
function array_set_key($array, $key = '', $valuekey = '')
{
$res = [];
while (list($k, $v) = each($array)) {
if ($key == '') {
$res[] = (($valuekey != '') ? $v[$valuekey] : $v);
} else {
$res[$v[$key]] = (($valuekey != '') ? $v[$valuekey] : $v);
}
}
reset($array);
return $res;
}/**
* 将多维数组中的某两个元素作为键名组成二维数组
* $array = [
* 0 => ['id'=>10,'title'=>'t10'],
* 1 => ['id'=>11,'title'=>'t11'],
* 2 => ['id'=>11,'title'=>'t12']
* ];
*
* $res = array_set_keys($array, 'id', 'title');
*
* 结果如下:
* $res = [
* 10 => [
* 't10' => ['id'=>10,'title'=>'t10']
* ],
*
* 11 => [
* 't11' => ['id'=>11,'title'=>'t11'],
* 't12' => ['id'=>11,'title'=>'t12']
* ]
* ];
* @param [type] $array [description]
* @param [type] $key1 [description]
* @param string $key2 [description]
* @param string $valuekey [description]
* @return [type] [description]
*/
function array_set_keys($array, $key1, $key2 = '', $valuekey = '')
{
$res = [];
while (list($k, $v) = each($array)) {
$k1 = $v[$key1];
$vl = ($valuekey != '') ? $v[$valuekey] : $v;
if ($key2 == '') {
$res[$k1][] = $vl;
} else {
$res[$k1][$v[$key2]] = $vl;
}
}
reset($array);
return $res;
}