您好我有以下数组列表我需要将其转换为按公司分组的内容并将类别显示为第二个数组。
[0] => Array
(
[company_id] => 1
[avatar] => '092EF7DB-B478-2EF5-1CC5-4A46D285B5F0.jpg'
[comp_name] => Hotel 1
[categories] => Array
(
[cat_+category_id] => Reception
[cat_+category_id] => Accommodation
)
[1] => Array
(
[company_id] => 8
[avatar] => ''
[comp_name] => Hotel 2
[categories] => Array
(
[cat_+category_id] => Reception
)
etc
下面的原始数组
0 => {#359 ▼
+"category_id": 10
+"company_id": 1
+"cat": "Reception"
+"comp_name": "Hotel 1"
+"avatar": "092EF7DB-B478-2EF5-1CC5-4A46D285B5F0.jpg"
}
1 => {#354 ▼
+"category_id": 12
+"company_id": 1
+"cat": "Accomodation"
+"comp_name": "Hotel 1"
+"avatar": "092EF7DB-B478-2EF5-1CC5-4A46D285B5F0.jpg"
}
2 => {#358 ▼
+"category_id": 10
+"company_id": 8
+"cat": "Reception"
+"comp_name": "Hotel 2"
+"avatar": null
}
3 => {#361 ▼
+"category_id": 10
+"company_id": 23
+"cat": "Reception"
+"comp_name": "Hotel 3"
+"avatar": null
}
4 => {#365 ▼
+"category_id": 12
+"company_id": 23
+"cat": "Accomodation"
+"comp_name": "Hotel 3"
+"avatar": null
你能告诉我如何在PHP中实现它 谢谢 达尼
答案 0 :(得分:1)
假设$originalArr
是您原始的一维数组,解决方案将您的一维数组转换为多维数组将是这样的:
$resultArr = array();
foreach($originalArr as $arr){
if(!isset($resultArr[$arr['company_id']])){
$resultArr[$arr['company_id']] = array('company_id' => $arr['company_id'],
'avatar' => $arr['avatar'],
'comp_name' => $arr['comp_name'],
'categories' => array('cat_' . $arr['category_id'] => $arr['cat'])
);
}else{
$resultArr[$arr['company_id']]['categories']['cat_' . $arr['category_id']] = $arr['cat'];
}
}
$resultArr = array_values($resultArr);
// display $resultArr array
var_dump($resultArr);