$data = [ [‘pid‘=>0,‘id‘=>1], [‘pid‘=>1,‘id‘=>2], [‘pid‘=>3,‘id‘=>4], [‘pid‘=>0,‘id‘=>3], ]; //对上面的数据进行递归排序(原生的写法) function genCate( $data, $pid = 0) { static $result = array(); foreach ($data as $key => $row) { if ($row[‘pid‘] == $pid) { $result[] = $row; $parent_id = $row[‘id‘]; foreach($data as $v){ if ($v[‘pid‘] == $parent_id) { $result[] = $v; } } } } return $result; } PHP递归的写法
function genCate( $data, $pid = 0) { static $result = array(); foreach ($data as $key => $row) { if ($row[‘pid‘] == $pid) { $result[] = $row; // $parent_id = $row[‘id‘]; genCate($data, $row[‘id‘]); /* foreach($data as $v){ if ($v[‘pid‘] == $parent_id) { $result[] = $v; } }*/ } } return $result; }
其实就是同一个数组两次循环 通过变动的是父id 不断找子元素
原文地址:https://www.cnblogs.com/wu-yu/p/9871981.html
时间: 2024-11-13 11:19:24