您的浏览器不支持canvas标签,请您更换浏览器

array操作系列

子孙树

$arr = [
	['id'=>1,'parent_id'=>0,'type'=>5],
	['id'=>2,'parent_id'=>1,'type'=>3],
	['id'=>3,'parent_id'=>0,'type'=>1],
	['id'=>4,'parent_id'=>3,'type'=>3],
];
var_dump(getSubTree($arr));

function getSubTree($data, $parent = 'parent_id', $son = 'id', $pid = 0)
    {
        $tmp = [];
        foreach ($data as $key => $value) {
            if ($value[$parent] == $pid) {
                $value['child'] = getSubTree($data, $parent, $son, $value[$son]);
                $tmp[] = $value;
            }
        }
        return $tmp;
    }

·

二维数组分组

$arr = [
	['id'=>1,'type'=>5],
	['id'=>2,'type'=>3],
	['id'=>3,'type'=>1],
	['id'=>4,'type'=>3],
];
var_dump(arrayGroupBy($arr, 'type'));

 function arrayGroupBy($arr, $key)
    {
        $grouped = [];
        foreach ($arr as $k => $value) {
            $grouped[$value[$key]][$k] = $value;
        }
        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('arrayGroupBy', $parms);
            }
        }
        return $grouped;
    }

·

二维数组排序

$arr = [
	['id'=>1,'sort'=>5],
	['id'=>2,'sort'=>3],
	['id'=>3,'sort'=>1],
];
array_multisort(array_column($arr, 'sort'), SORT_ASC, $arr);
var_dump($arr);

·

交叉转化

$arr = [
    'id',
    1,
    'type',
    2
];
var_dump(hashMake($arr));
function hashMake(array $hashData): array
{
    $return = [];
    $count  = count($hashData);
    for ($i = 0; $i < $count; $i += 2) {
        $return[$hashData[$i]] = $hashData[$i + 1];
    }
    return $return;
}

LW放下的博客
请先登录后发表评论
  • latest comments
  • 总共0条评论