1

I have documents stored on my server, and their information like title, filepath, date, category, etc., stored in a database. My goal is to be able to group the documents together by their categories. The document's category is stored in the database as a string like "COVID-19 | Guidance | Mortuary Affairs", and I want to convert it to an array like the following:

[
  "COVID-19" => [
    "Guidance"=> [
      "Mortuary Affairs" => [
        // Where the document info will be
      ]
    ]
  ]
]

The first step would be looping through the documents and exploding each category by the | delimiter:

foreach($all_documents as $document)
{
  $categories = array_map('trim', explode('|', $document['category']));
}

Doing so results in the following:

[
  "COVID-19",
  "Guidance",
  "Mortuary Affairs"
]

How would I then take this array and turn it into the nested array displayed at the top?

trincot
  • 317,000
  • 35
  • 244
  • 286
tyguy
  • 358
  • 2
  • 4
  • 16
  • 1
    See also [this question](https://stackoverflow.com/questions/49563864/string-to-multidimensional-recursive-array-in-php) – Syscall Feb 19 '21 at 18:59

1 Answers1

1

After the creation of the array with categories, you could iterate those categories and "drill" down a result object with a node-reference -- creating any missing properties, and then referencing them. Finally append the document to the deepest node's array (so multiple documents can end up at the same place):

$result = [];
foreach ($all_documents as $document) {
  $categories = array_map('trim', explode('|', $document['category']));
  $node =& $result; // reference the "root"
  $last = array_pop($categories);
  foreach ($categories as $category) {
      if (!isset($node[$category])) $node[$category] = []; // create child
      $node =& $node[$category]; // change the reference to the child
  }
  $node[$last][] = $document; // append document to this list
}

At the end $result will have the desired hierarchical structure.

trincot
  • 317,000
  • 35
  • 244
  • 286