如何将指定JSON数据集转换为PHP层级菜单树结构?
转换后的层级PHP数组
直接给你生成好的目标PHP数组结构:
<?php $menuTree = [ 'technic' => [ 'TV' => [ 'Sony' => [ 'Some_model_acd', 'Some_model_bcd' ], 'LG' => [ 'Some_model_zcd', 'Some_model_bcd' ] ] ], 'phones' => [ 'smartphones' => [ 'Apple' => [ 'some_model' ] ], 'smartphones_small_disp' => [ 'Apple' => [ 'some_model 1' ], 'Samsung' => [ 'some_model 2' ] ], 'smartphones_large_disp' => [ 'Apple' => [ 'some_model 3' ], 'Samsung' => [ 'some_model 4' ] ] ] ]; ?>
自动转换的PHP代码(可复用)
如果后续JSON数据有更新,你可以用这段代码自动生成层级数组,不用手动修改:
<?php // 原始JSON数据 $jsonData = '[ { "type": "technic", "product_cat": "TV", "brand_name":"Sony", "Model":"Some_model_acd" }, { "type": "technic", "product_cat": "TV", "brand_name":"Sony", "Model":"Some_model_bcd" }, { "type": "technic", "product_cat": "TV", "brand_name":"LG", "Model":"Some_model_zcd" }, { "type": "technic", "product_cat": "TV", "brand_name":"LG", "Model":"Some_model_bcd" }, { "type": "phones", "product_cat": "smartphones", "brand_name":"Apple", "Model":"some_model" }, { "type": "phones", "product_cat": "smartphones_small_disp", "brand_name":"Apple", "Model":"some_model 1" }, { "type": "phones", "product_cat": "smartphones_small_disp", "brand_name":"Samsung", "Model":"some_model 2" }, { "type": "phones", "product_cat": "smartphones_large_disp", "brand_name":"Apple", "Model":"some_model 3" }, { "type": "phones", "product_cat": "smartphones_large_disp", "brand_name":"Samsung", "Model":"some_model 4" } ]'; // 解码JSON为PHP数组 $products = json_decode($jsonData, true); // 初始化空的菜单树 $menuTree = []; // 遍历每个产品,逐层构建层级结构 foreach ($products as $product) { $type = $product['type']; $cat = $product['product_cat']; $brand = $product['brand_name']; $model = $product['Model']; // 确保每一层级都存在,不存在则创建空数组 if (!isset($menuTree[$type])) { $menuTree[$type] = []; } if (!isset($menuTree[$type][$cat])) { $menuTree[$type][$cat] = []; } if (!isset($menuTree[$type][$cat][$brand])) { $menuTree[$type][$cat][$brand] = []; } // 将型号添加到对应品牌的数组中 $menuTree[$type][$cat][$brand][] = $model; } // 打印结果(可选,用于验证) echo '<pre>'; print_r($menuTree); echo '</pre>'; ?>
这段代码逻辑很直观:先把JSON转成PHP数组,然后循环每个产品,检查type→product_cat→brand_name每一层是否存在,不存在就创建空数组,最后把型号添加到对应品牌的数组里。运行后就能得到你想要的层级结构。
内容的提问来源于stack exchange,提问作者gluon
相关产品推荐
相关产品推荐

