无限分类按分类层级重新排序方法

初始数据:

$values = [
    0 => ["id" => 1, "product_style_name" => "话筒", "pid" => 0],
    1 => ["id" => 17, "product_style_name" => "配件", "pid" => 0],
    2 => ["id" => 2, "product_style_name" => "有线话筒", "pid" => 1],
    3 => ["id" => 18, "product_style_name" => "无线话筒", "pid" => 1],
    4 => ["id" => 6, "product_style_name" => "音频配件", "pid" => 17],
    5 => ["id" => 14, "product_style_name" => "无线配件", "pid" => 17],
    6 => ["id" => 20, "product_style_name" => "电视配件", "pid" => 17],
    7 => ["id" => 21, "product_style_name" => "音频配件01", "pid" => 6],
    8 => ["id" => 22, "product_style_name" => "电视配件01", "pid" => 20],
    9 => ["id" => 23, "product_style_name" => "无线配件01", "pid" => 14],
];

目标输出数据:

$result = array (
  0 => array ('id' => 1,'product_style_name' => '话筒','pid' => 0,),
  1 => array ('id' => 2,'product_style_name' => '有线话筒','pid' => 1,),
  2 => array ('id' => 18,'product_style_name' => '无线话筒','pid' => 1,),
  3 => array ('id' => 17,'product_style_name' => '配件','pid' => 0,),
  4 => array ('id' => 6,'product_style_name' => '音频配件','pid' => 17,),
  5 => array ('id' => 21,'product_style_name' => '音频配件01','pid' => 6,),
  6 => array ('id' => 14,'product_style_name' => '无线配件','pid' => 17,),
  7 => array ('id' => 23,'product_style_name' => '无线配件01','pid' => 14,),
  8 => array ('id' => 20,'product_style_name' => '电视配件','pid' => 17,),
  9 => array ('id' => 22,'product_style_name' => '电视配件01','pid' => 20,),
);

实现方法:

/**
 * 分类层级重新排序
 *
 * @param array $array
 * @param int $pid
 *
 * @return array
 */
function resort($array, $pid = 0)
{
    $result = [];
    foreach ($array as $key => $item) {
        if ($item['pid'] == $pid) {
            array_push($result, $item);
            $result = array_merge($result, resort($array, $item['id']));
        }
    }

    return $result;
}

$result = resort($values);
print_r($result);

 

你可能感兴趣的:(PHP)