PHP数组按类别分组

时间:2019-05-21 20:08:26

标签: php

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

今天,我多次显示每个商店,一行仅显示一个类别。

我如何将商店分组,创建其类别的数组,以便商店仅显示一次并具有多个类别?

这是我的尝试:

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"
        }
    ]
},

我尝试在一段时间内尝试创建类别,但有php警告:end() expects parameter 1 to be array, null given

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

1 个答案:

答案 0 :(得分:1)

我相信您在将返回的MySQL行返回到json_encodehttps://3v4l.org/d4Wf2

时正在寻找类似的东西

这会将商店放置在1临时$storeTracker array中,商店ID为array key(这假设商店ID在您要取回的每条记录中都是常数,并且始终相同)。然后,您可以从此处检查array key(商店ID)是否已经存在,如果存在,请继续向商店添加类别(如果类别尚不存在)。完成此操作后,您可以解析到json_encode以创建一个有效的JSON对象以返回。当然,可以使用一种更雄辩的方法来实现此目的,但这展示了array的操作以及为案例数据尝试进行分组的方法。

<?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;

将为您提供有效的JSON https://jsonlint.com/

[{
    "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"
    }]
}]