将二维数组的行转换为多级组

问题描述 投票:0回答:1

我早些时候试图问这个问题,但没有提供足够的信息......

我正在从数据库中提取信息。我拉的每一行看起来都是这样的,

{
    "group":"admin",
    "center":"equipment",
    "section":"bucket",
    "tab":"overview"
}

我需要以下信息,“中心”、“部分”和“选项卡”。

目前,我使用“array_push”使用此信息创建一个数组。代码看起来像这样,

for ($y = 0; $y < count($infos); $y++) {
    $templist = array();
    array_push($templist, $infos[$y]['center']);
    array_push($templist, $infos[$y]['section']);
    array_push($templist, $infos[$y]['tab']);
    array_push($tempmasterlist, $templist);

并在我使用 json_encode() 时显示此内容

[
   ["center1", "section1", "tab1"],
   ["center2", "section1", "overview"],
   ["center1", "section1", "tab2"]
]

我需要生成的 json 看起来像这样,

{
    "center1": [
        "section1",
        ["tab1", "tab2"]
    ],
    "center2": [
        "section1",
        ["tab3"]
    ]
}

基本上,我想对它们进行动态分组,以便可以轻松检索它们。 一个中心可以有多个部分,一个部分可以有多个选项卡。根据用户的不同,可能有多个中心、部分或选项卡,因此我无法对任何内容进行硬编码。

php arrays multidimensional-array grouping
1个回答
2
投票

你不需要

array_push
。您只需使用结果行中的相应列作为
$tempmasterlist
中的键。

foreach ($infos as $row) {
    $tempmasterlist[$row['center']][$row['section']][] = $row['tab'];
}
© www.soinside.com 2019 - 2024. All rights reserved.