How do I combine inner arrays of a 2D array based on first identical value?

foreach ($files as $file) {
    $filename = substr($file, 0, strrpos($file, '.')) . '.jpg'; // file name with .jpg extension

    // lots of irrelevant code between here

    if (isset($filename)) {
        $newProcessedFileNames[] = $filename;
    }
}

$testArray = [];
$result = array_values($newProcessedFileNames);
foreach ($result as $row) {
    $string = explode('\\', $row);
    $testArray[] = $string;
}
prettyPrint($testArray); // just a print_r function wrapped in pre tags

I am working on a project that compresses images and (eventually) rewrites filenames to a database, based on a GUID.

I have tried various loops and array functions to get the array structure that I want, but without success.

$newProcessedFileNames is an array containing $filename strings.

Each $filename is structured as: {DIRECTORY}\\{FILENAME}.jpg or GUID\\FILENAME.jpg if you will.

Example: 0ec3d6c6-7655-4f90-b290-86ad0e201d8f\\1671630653-20221221-134503.jpg

The structure I currently get:

Array
(
    [0] => Array
        (
            [0] => 0ec3d6c6-7655-4f90-b290-86ad0e201d8f
            [1] => 1671630653-20221221-134503.jpg
        )

    [1] => Array
        (
            [0] => 0ec3d6c6-7655-4f90-b290-86ad0e201d8f
            [1] => 1671630653-20221221-135652.jpg
        )

    [2] => Array
        (
            [0] => 0ec3d6c6-7655-4f90-b290-86ad0e201d8f
            [1] => 1671630653-20221221-141137.jpg
        )
.
.
.
    [87] => Array
        (
            [0] => 1a8f3b9a-af6a-44be-b3f0-3e1c723f161e
            [1] => 1669761126-20221129-204008.jpg
        )

    [88] => Array
        (
            [0] => 1a8f3b9a-af6a-44be-b3f0-3e1c723f161e
            [1] => 1669761126-20221129-204017.jpg
        )

    [89] => Array
        (
            [0] => 1a8f3b9a-af6a-44be-b3f0-3e1c723f161e
            [1] => 1669761126-20221129-204027.jpg
        )

)

The structure I am trying to get:

Array
(
    [0ec3d6c6-7655-4f90-b290-86ad0e201d8f] => Array
        (
            [0] => 1671630653-20221221-134503.jpg
            [1] => 1671630653-20221221-135652.jpg
            [2] => 1671630653-20221221-141137.jpg
        )
.
.
.
    [1a8f3b9a-af6a-44be-b3f0-3e1c723f161e] => Array
        (
            [0] => 1669761126-20221129-204008.jpg
            [1] => 1669761126-20221129-204017.jpg
            [2] => 1669761126-20221129-204027.jpg
        )
)

This is probably super simple and I’m most likely over-thinking it, but I can’t wrap my head around it at the moment.

>Solution :

$testArray = [];
$result = array_values($newProcessedFileNames);
foreach ($result as $row) {
    $string = explode('\\', $row);
    $id = $string[0];
    $testArray[$id][] = $string[1];
}

Leave a Reply