Andrew Fletcher published: 18 May 2022 1 minute read
To sort through a multidimensional array seems to be a function that I occasionally call on. Handy to have referenced here:
/**
* Loop through a multi dimensional array
*
* @param array $haystack
* Data array.
*/
protected function sortMultiDimensionalArray($haystack)
{
foreach ($haystack as $key => $item) {
// If $item is an array and the number of children is greater to one
// keep looping through the array.
if (is_array($item) && count($haystack[$key]) > 1) {
$this->sortMultiDimensionalArray($haystack[$key]);
}
// If count is equal to one then load it in to the get_value array.
elseif (is_array($item) && count($haystack[$key]) == 1) {
$k = key($item);
if (is_array($item[$k])) {
$k2 = key($item[$k]);
$this->get_value[] = $item[$k][$k2];
}
else {
$this->get_value[] = $item[$k];
}
}
// Not an array.
elseif (!is_array($item)) {
$this->get_value[] = $item;
}
}
}
Related articles
Andrew Fletcher
•
31 May 2024
Connecting AWS S3 with Docker for Drupal 10
Recently, I encountered an issue where my local Docker environment refused to connect to AWS S3, although everything worked seamlessly in AWS-managed environments. This challenge was not just a technical hurdle; it was a crucial bottleneck that needed resolution to ensure smooth Drupal deployments...
Andrew Fletcher
•
09 May 2024
Accessing nested paragraph fields in Drupal: a step-by-step reference
The issue – I have a content type that includes an entity reference revisions field named field_introduction. This field points to a paragraph, which itself contains a text field also named field_introduction, of the type Text (formatted, long). How can I access the content stored in this...
Andrew Fletcher
•
09 May 2024
How to retrieve the current menu title in Drupal – a developer’s reference
When building a theme in Drupal, it's often necessary to adapt your site’s UI dynamically based on the context in which a user is navigating. One such piece of dynamic content is the menu title. Achieving this can be a bit tricky due to the layered nature of its routing and menu systems. This...