0

I have a flat array containing filenames. I need to group the filenames by their leading substring and form pipe-delimited elements.

Sample input:

$j = [
    'ma_1_49812_5318.jpg',
    'ma_1_49812_5319.jpg',
    'ma_1_49813_5320.jpg',
    'ma_1_49813_5321.jpg',
];

Desired result:

[
    'ma_1_49812_5318.jpg|ma_1_49812_5319.jpg',
    'ma_1_49813_5320.jpg|ma_1_49813_5321.jpg',
]

My coding attempt:

$entry = array();
$lastjs = '';
$jx ='';
foreach ($j as $group) {
    $jx = explode("_", $group)[2];
    if ($jx == $lastjs || $lastjs == '') {
        $entry[] = $group;
        $lastjs = $jx;
    }
    else
    {
        $entry[] = $group;
        $lastjs = $jx;
    }
}

My incorrect result:

(
    [0] => ma_1_49812_5318.jpg
    [1] => ma_1_49812_5319.jpg
    [2] => ma_1_49813_5320.jpg
    [3] => ma_1_49813_5321.jpg
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Assaf Schwartz
  • 119
  • 1
  • 7
  • You are currently doing the _exact same_ thing in your if and your else branch - makes little sense, you might as well just have done the thing without applying _any_ conditions in the first place. – CBroe Mar 06 '23 at 11:04
  • You could use `$jx` as key for a helper array to group your data under, but ... _"what im trying to accomplish is to add the name of the photos to same row like : a_1_777_1000.jpg|a_1_777_1001.jpg"_ - not a good idea to begin with; you should rather _properly_ normalize your data. (See also: [Is storing a delimited list in a database column really that bad?](https://stackoverflow.com/q/3653462/1427878)) – CBroe Mar 06 '23 at 11:06
  • thanks CBroe, for my situation its what i need , other ways is to add the photos to other mysql table so i prefer in same row with other data, i want it to be the fastest way to read – Assaf Schwartz Mar 06 '23 at 11:25

1 Answers1

0

When you encounter a new real estate property, push a new reference into the result array. When you re-encounter a real estate property, concatenate the reference variable with a pipe then the new value. Using this technique, you do not need to use temporary keys in the result array (this also eliminates the need to call array_values() to re-indes the result array).

Code: (Demo)

$result = [];
foreach ($j as $filename) {
    $groupBy = preg_replace('/_[^_]+$/', '', $filename); // remove unique filename ending
    if (!isset($ref[$groupBy])) {
        $ref[$groupBy] = $filename;
        $result[] = &$ref[$groupBy];
    } else {
        $ref[$groupBy] .= "|$filename";
    }
}
var_export($result);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136