I have a list of stores and they can have multiple categories.
Today i display each store multiple times, one line with only one category.
How can i group the stores, creating an array of their categories, so the store is displayed only one time and have their multiple categories ?
This is my attempt:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push(
$stores,
[
"id"=> $row["id"],
"name"=> $row["nome"],
"categories"=> array([
"name"=> $row["categories"]
//how can i have an array of categories
])
]
);
}
This is how i display the json result:
{
id: 74,
name: "First Store",
categories: [
{
name: "Clothes"
}
]
},
{
id: 1,
name: "Second Store",
categories: [
{
name: "Food"
}
]
},
{
id: 1,
name: "Second Store",
categories: [
{
name: "Toys"
}
]
},
This is how i need to show the Json:
{
id: 74,
name: "First Store",
categories: [
{
name: "Clothes"
}
]
},
{
id: 1,
name: "Second Store",
categories: [
{
name: "Food"
},
{
name: "Toys"
}
]
},
In my attempt i try inside the while to create the categories but have a php warning: end() expects parameter 1 to be array, null given
if( isset($stores) ) {
if( end($stores['id']) != $row["id"] ) {
array_push($category_array, $row["categories"]);
}
}