phparraysmultidimensional-arraygrouping

Convert rows of a 2d array into multi-level groups


I attempted to ask this question earlier but did not provide enough information...

I am pulling information out of a database. Each row that I pull looks like this,

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

I need the following information, "Center", "section", and "tab".

Currently, I use "array_push" to create an array with this info. The code looks like this,

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

and displays this when I use json_encode()

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

I need the resulting json to look like this,

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

Basically, I want to dynamically group these properly so that they can be easily retrieved. A center can have multiple sections, and a section can have multiple tabs. Depending on the user, there can be multiple centers, sections, or tabs so I am not able to hardcode anything.


Solution

  • You don't need to array_push. You can just use the appropriate column from your result rows as keys in $tempmasterlist.

    foreach ($infos as $row) {
        $tempmasterlist[$row['center']][$row['section']][] = $row['tab'];
    }