PHP数组按类别分组

PHP数组按类别分组,php,Php,我有一个商店列表,它们可以有多个类别 今天,我将每家店铺显示多次,一行只显示一个类别 我如何对商店进行分组,创建其类别的数组,以便商店只显示一次并具有多个类别 这是我的尝试: while ($row = $query->fetch(PDO::FETCH_ASSOC)) { array_push( $stores, [ "id"=> $row["id"], "name"=> $row["no

我有一个商店列表,它们可以有多个类别

今天,我将每家店铺显示多次,一行只显示一个类别

我如何对商店进行分组,创建其类别的数组,以便商店只显示一次并具有多个类别

这是我的尝试:

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
            ])
        ]
    );
}
以下是我显示json结果的方式:

{
    id: 74,
    name: "First Store",
    categories: [
        {
            name: "Clothes"
        }
    ]
},
{
    id: 1,
    name: "Second Store",
    categories: [
        {
            name: "Food"
        }
    ]
},
{
    id: 1,
    name: "Second Store",
    categories: [
        {
            name: "Toys"
        }
    ]
},

这就是我需要显示Json的方式:

{
    id: 74,
    name: "First Store",
    categories: [
        {
            name: "Clothes"
        }
    ]
},
{
    id: 1,
    name: "Second Store",
    categories: [
        {
            name: "Food"
        },
        {
            name: "Toys"
        }
    ]
},

在我的尝试中,我尝试在while中创建类别,但出现了一个php警告:
end()希望参数1是数组,如果给定空值

if( isset($stores) ) {
    if(  end($stores['id']) != $row["id"] )  {
            array_push($category_array, $row["categories"]);
    }
} 

我相信在处理返回的
MySQL
行到
json\u encode
时,您正在寻找类似的东西:

这将把存储放在1 temp
$storeTracker array
中,存储id作为
数组键
(这假设存储id在您要返回的每个记录中都是常量,并且始终相同)。然后,您可以从这里检查
数组键
(存储id)是否已经存在,如果已经存在,则继续向存储添加类别(如果类别还不存在)。完成此操作后,您可以解析到
json\u encode
,以创建要返回的有效
json
对象。诚然,可能有一种更雄辩的方法来实现这一点,但这展示了
数组
操作以及尝试为您的案例分组数据的其他方法

<?php

// Data coming from MySQL Database
$rowData = [];
$rowData[] = ['id' => 74, 'name' => 'First Store', 'categories' => 'Food'];
$rowData[] = ['id' => 74, 'name' => 'First Store', 'categories' => 'DVDs'];

$rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Food'];
$rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Toys'];
$rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Toys'];
$rowData[] = ['id' => 1, 'name' => 'Second Store', 'categories' => 'Clothing'];

$rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Toys'];
$rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Clothing'];
$rowData[] = ['id' => 3, 'name' => 'Third Store', 'categories' => 'Clothing'];

/**
 * Check if store category name already added to store record
 */
function categoryExistsAlready($categories, $category) {
    foreach($categories as $key => $catArr) {
        if(strtolower($catArr['name']) === strtolower($category)) {
            return true;
        }
    }
    return false;
}

$storeTracker = [];
foreach($rowData as $key => $storeData) {

    $storeCategory = $storeData['categories'];
    $storeId = $storeData['id'];

    // If store exists, add category to categories array
    if (array_key_exists($storeId, $storeTracker)) {
        if (!categoryExistsAlready($storeTracker[$storeId]['categories'], $storeCategory)) {
            $storeTracker[$storeId]['categories'][] = ['name' => $storeCategory];
        }
        continue;
    }

    // Update store categories to be array with category
    $storeData['categories'] = [];
    $storeData['categories'][] = ['name' => $storeCategory];

    // Add store data to overall tracking array
    $storeTracker[$storeId] = $storeData;
}

// Format JSON response
$jsonReturn = '[';
$i = count($storeTracker);
foreach($storeTracker as $storeId => $storeData) {
    $i--;
    $jsonReturn .= json_encode($storeData);
    // Determine last comma separating objects
    if ($i > 0) {
        $jsonReturn .= ',';
    }
}
$jsonReturn .= ']';

echo $jsonReturn;

我进一步思考了下面的答案,是否有一个原因使您无法编辑SQL查询以按存储id对不同的类别进行分组以获得类别数组等?
[{
    "id": 74,
    "name": "First Store",
    "categories": [{
        "name": "Food"
    }, {
        "name": "DVDs"
    }]
}, {
    "id": 1,
    "name": "Second Store",
    "categories": [{
        "name": "Food"
    }, {
        "name": "Toys"
    }, {
        "name": "Clothing"
    }]
}, {
    "id": 3,
    "name": "Third Store",
    "categories": [{
        "name": "Toys"
    }, {
        "name": "Clothing"
    }]
}]