我想从我的数据库中回显多维数组,我试图在 stackoverflow 中搜索,但我无法很好地实现。这是我的数组:Array ( [0] => Array ( [product_name] => BMW [category_name] => Car ) [1] => Array( [product_name] => Jaguar [category_name] => Car ) [2] => Array( [product_name] => Toyota [category_name] => Car ) [3] => Array ( [product_name] => Jeep [category_name] => Car ) [4] => Array ( [product_name] => Ducati [category_name] => Bike ))我需要将这个数组分组如下:Array( [0] => Array( [category_name] => Car [product_name] => Array( [0] => Array( [product_name] => BMW ) [1] => Array( [product_name] => Toyota ) [2] => Array( [product_name] => Jaguar ) [3] => Array( [product_name] => Jeep ))) [1] => Array ( [category_name] => Bike [product_name] => Array ( [0] => Array ( [product_name] => Ducati )) )然后回显到 html 列表:汽车: - 宝马 - 丰田 - 捷豹 - 吉普自行车: - 杜卡迪请帮忙..谢谢
3 回答
慕勒3428872
TA贡献1848条经验 获得超6个赞
你可以使用array_map,array_column
$res=[];
array_map(function($v) use (&$res){
$res[$v['category_name']][] = ['product_name' => $v['product_name']];
}, $arr);
foreach($res as $type => $value){
echo $type.':-'.implode(',',array_column($value, 'product_name'));
}
胡子哥哥
TA贡献1825条经验 获得超6个赞
希望能帮助到你。
$t = [];
foreach($input_array as $v) {
$t[$v['category_name']] [] = $v['product_name'];
}
$out = [];
foreach ($t as $key => $val) {
$out[$key] = implode(',',$val);
}
echo $out['car'];
echo "\n";
echo $out['bike'];
- 3 回答
- 0 关注
- 172 浏览
添加回答
举报
0/150
提交
取消