我正在创建一家电子商务网站,需要在特定数组中提供商店所拥有的类别。目前从mysql表中检索到的数据如果数组具有不同的子类,则包含相同类别ID的不同数组项。我必须将相同类别ID收集在同一个数组中,并为子类创建嵌套数组。此代码位于laravel 4.2上。以下是当前数据格式:
以下是我从上述代码中获得的输出结果:
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Dairy Whiteners"
],
"total_items": 69
},
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Tea & Coffee"
],
"total_items": 69
},
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Concentrates - Tang etc"
],
"total_items": 69
},
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Tea & Coffee"
],
"total_items": 28
},
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Concentrates - Tang etc"
],
"total_items": 28
}
]
Here is what I need ,
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Dairy Whiteners" , "Concentrates - Tang etc" , "Tea & Coffee"
],
"total_items": 69
} ,
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Tea & Coffee" , "Concentrates - Tang etc"
],
"total_items": 28
}
]
The code I wrote for the above ,
// For the current categories create a common array for subcategories for same categories
$filteringSelectedCategories = [];
$subCategoriesNamesLocal = [];
$innerIndex = 0;
for ($i = 0; $i < count($selectedCategories); $i++) {
// to prevent undefined offset error
if (!isset($selectedCategories[$i + 1])) {
continue ;
// if 6 don't exist then deal with 5
}
// if the id of two items is same then push that sub category name in the same array
if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) {
array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']);
}
// if the id is different then push the array values with the sub category name in an array
else {
$filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id'];
$filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name'];
$filteringSelectedCategories[$innerIndex]['sub_category_names'] = $subCategoriesNamesLocal;
$filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items'];
// nullify the array after assigning the value
$subCategoriesNamesLocal = [];
// increment the new array index
$innerIndex = $innerIndex + 1;
}
}
以下是我从上述代码中获得的输出结果:
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
[
"Dairy Whiteners"
],
[
"Tea & Coffee"
]
],
"total_items": 69
}
]