I have following array and want to merge array value where loc
(location) match.
In other words I want to merge array value(text) where loc
is similar
Here is my current array
Array
(
[0] => Array
(
[id] => 11
[column_name] => Accommodation
[text] => school
[loc] => B3
[match] => 3
)
[1] => Array
(
[id] => 12
[column_name] => Accommodation
[text] => test
[loc] => B3
[match] => 3
)
[2] => Array
(
[id] => 13
[column_name] => Incidental Expenses
[text] => you
[loc] => C3
[match] => 3
)
)
Here is my expected output ( merge "text" according to "loc" , because location match)
Array
(
[0] => Array
(
[id] => 11
[column_name] => Accommodation
[text] => school , test
[loc] => B3
[match] => 3
)
[1] => Array
(
[id] => 13
[column_name] => Incidental Expenses
[text] => you
[loc] => C3
[match] => 3
)
)
I tried with following code but not working
foreach ($result as $key =>$element) {
foreach ($result as $search_key => $search_array) {
if ($search_array['loc'] == $element['loc']) {
if ($search_key != $key) {
if($search_key == '1'){
$run = $element['text'];
$mystring3 = explode(', ',$run);
foreach ($mystring3 as $fast){
}
}
}
}
}
CodePudding user response:
Try to use below,
$inputAry = [
[
'id' => 11,
'column_name' => 'Accommodation',
'text' => 'school',
'loc' => 'B3',
'match' => 3
], [
'id' => 12,
'column_name' => 'Accommodation',
'text' => 'test',
'loc' => 'B3',
'match' => 3
], [
'id' => 13,
'column_name' => 'Incidental Expenses',
'text' => 'you',
'loc' => 'C3',
'match' => 3
]
];
$formattedAry = [];
foreach ($inputAry as $ary) {
$formattedArykey = array_search($ary['loc'], array_column($formattedAry, 'loc'));
if ($formattedArykey !== false) {
$formattedAry[$formattedArykey]['text'] .= ', ' . $ary['text'];
} else {
$formattedAry[] = $ary;
}
}
print_r($formattedAry);