I'm doing a REST api with Lumen framework.
One api call give me all my categories of product :
{
"categories": [
{
"id": 1,
"name": "Boissons",
"parent": null,
"categories": [
{
"id": 3,
"name": "Sans alcool",
"parent": 1,
"categories": []
},
{
"id": 4,
"name": "Bières",
"parent": 1,
"categories": []
},
{
"id": 5,
"name": "Spiritueux",
"parent": 1,
"categories": [
{
"id": 6,
"name": "Rhums",
"parent": 5,
"categories": []
},
{
"id": 7,
"name": "Whiskys",
"parent": 5,
"categories": []
}
]
}
]
},
{
"id": 2,
"name": "Gastronomie",
"parent": null,
"categories": []
}
]
}
I want to delete categories that don't contain any product.
I do :
$models = $this->removeCategoriesWithoutProduct($company, $models);
Where the method removeCategoriesWithoutProduct
is describe below :
private function removeCategoriesWithoutProduct($company, $models)
{
for ($i = count($models)- 1; $i >= 0; $i--) {
// get number of product in category
$count = $this->productRepository->countCompanyCategory($company, $models[$i]->id);
if ($count == 0 && count($models[$i]->categories) == 0) {
Log::debug('No product and no child categories', ['model' => $models[$i]->name]);
$models[$i] = null;
} else {
// check child categories
$models[$i]->categories = $this->removeCategoriesWithoutProduct($company, $models[$i]->categories);
// if category without product and no one child contain product
// delete the parent category (the current one)
if ($count == 0) {
$delete = true;
foreach ($models[$i]->categories as $cat) {
$delete = $cat == null;
if (!$delete) {
break;
}
}
if ($delete) {
Log::debug('No product and all child categories empty', ['model' => $models[$i]->name]);
$models[$i] = null;
}
}
}
}
return $models;
}
And then I get this result :
{
"categories": [
{
"id": 1,
"name": "Boissons",
"parent": null,
"categories": [
null,
null,
{
"id": 5,
"name": "Spiritueux",
"parent": 1,
"categories": [
null,
{
"id": 7,
"name": "Whiskys",
"parent": 5,
"categories": []
}
]
}
]
},
null
]
}
If I use unset
instead of assign null value I get this result :
{
"categories": [
{
"id": 1,
"name": "Boissons",
"parent": null,
"categories": {
"2": {
"id": 5,
"name": "Spiritueux",
"parent": 1,
"categories": {
"1": {
"id": 7,
"name": "Whiskys",
"parent": 5,
"categories": []
}
}
}
}
}
]
}
I don't understand why my sub array is fucked up ? I want this result :
{
"categories": [
{
"id": 1,
"name": "Boissons",
"parent": null,
"categories": [
{
"id": 5,
"name": "Spiritueux",
"parent": 1,
"categories": [
{
"id": 7,
"name": "Whiskys",
"parent": 5,
"categories": []
}
]
}
]
}
]
}