isset()
быстрее array_search()
Код: ( Демо )
$array = [
"prefix1 foo",
"prefix2 bar",
"prefix1 aaa",
"prefix2 bbb",
"prefix3 ccc",
"prefix1 111",
"prefix2 222"
];
foreach ($array as $v) {
[$prefix, $value] = explode(' ', $v, 2); // explode and perform "array destructuring"
if (isset($batch[$prefix])) { // check if starting new batch
$result[] = $batch; // store old batch
$batch = [$prefix => $value]; // start new batch
} else{
$batch[$prefix] = $value; // store to current batch
}
}
$result[] = $batch; // store final batch
var_export($result);
или
foreach ($array as $v) {
[$prefix, $value] = explode(' ', $v, 2);
if (isset($batch[$prefix])) {
$result[] = $batch;
unset($batch);
}
$batch[$prefix] = $value;
}
$result[] = $batch;
Выход:
array (
0 =>
array (
'prefix1' => 'foo',
'prefix2' => 'bar',
),
1 =>
array (
'prefix1' => 'aaa',
'prefix2' => 'bbb',
'prefix3' => 'ccc',
),
2 =>
array (
'prefix1' => '111',
'prefix2' => '222',
),
)