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
)