How can multidimensional arrays be utilized in PHP to organize and sort images by category and position in the file name?

To organize and sort images by category and position in the file name using multidimensional arrays in PHP, you can create an array where the keys represent the categories and the values are arrays containing the image filenames. You can then sort the images within each category based on their position in the filename using a custom sorting function. This approach allows for efficient organization and sorting of images based on both category and position.

<?php
// Sample image filenames
$imageFiles = [
    "category1_image3.jpg",
    "category2_image2.jpg",
    "category1_image1.jpg",
    "category2_image1.jpg",
    "category1_image2.jpg",
];

// Initialize a multidimensional array to store images by category
$imagesByCategory = [];

// Iterate through image filenames and populate the multidimensional array
foreach($imageFiles as $image) {
    $parts = explode("_", $image);
    $category = $parts[0];
    $position = (int)filter_var($parts[1], FILTER_SANITIZE_NUMBER_INT);

    $imagesByCategory[$category][] = [
        'filename' => $image,
        'position' => $position
    ];
}

// Sort images within each category based on position in the filename
foreach($imagesByCategory as $category => &$images) {
    usort($images, function($a, $b) {
        return $a['position'] - $b['position'];
    });
}

// Output the organized and sorted images
print_r($imagesByCategory);
?>