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?

1
  • 1
    See also this question Commented Feb 19, 2021 at 18:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.