PHP处理没有父子级关系的数据为树状结构数据,对二维数组以某个键值相同的分组合并,最终形成树状结构数据
1、从数据库获取的数据
2、对查询出来的数据按键值归类
<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Log;
class Data extends Controller {
public function getTreeData(){
$res = Db::table('table_name')
->select();
$erArr = self::getRepeatValGroup($res,'platform');
Log::info($erArr);
$newArr = [];
foreach($erArr as $erK => $erV){
$arr1 = [];
foreach ($erV as $k => $v) {
$arr1[$v['area']][] = $v;
}
$newArr[$erK][]=$arr1;
}
return json($newArr);
}
//$arr= 一个数组。$keys 是该数组里面的某一个值 该自定义函数主要是对二维数组里面的某一个值进行分组
public function getRepeatValGroup($arr,$keys)
{
if(!is_array($arr) || !$keys) {
return false;
}
$temp = array();
foreach($arr as $key=>$val) {
$temp[$val[$keys]][] = $val;
}
return $temp;
}
}
3、页面通过ajax请求接口,使用第三方书组件
$.ajax({
type:"get",
url:"/index/channels/getPlatform",
success:function(data){
let platformArr = []
Object.keys(data).map(platform => {
let areaArr = []
data[platform].forEach(areaKey =>{
//console.log('.........................')
//console.log(areaKey)
Object.keys(areaKey).map(area => {
//console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
///console.log(area)
//console.log('-------------区域-----------------------')
//console.log(areaKey[area])
let countryArr = []
areaKey[area].forEach(country =>{
countryArr.push({
id:country.channel_no,
active: country.active,
//parentId:data2[0].area,
label:country.country
})
})
areaArr.push({
label:area,
children:countryArr
})
})
})
if(platform == 'Amazon'){
platformArr.unshift({
label: 'Amazon',
children:areaArr
})
}else{
platformArr.push({
label: platform,
children:areaArr
})
}
})
}
})