0

I have following array inside foreach loop and I want to merge array value(append with comma) where "key value" (column_name,match,coll) is same/duplicate. In short I want to combine duplicate array values. How can I do this? Here is my current array

Array
(
    [id] => 86
    [column_name] => Accommodation
    [text] => hotel
    [match] => 2
    [coll] => 1
)

Array
(
    [id] => 87
    [column_name] => Accommodation
    [text] => staff
    [match] => 2
    [coll] => 1
)

Array
(
    [id] => 91
    [column_name] => Accommodation
    [text] => marriot
    [match] => 3
    [coll] => 1
)

My expected result:

Array
(
    [id] => 86
    [column_name] => Accommodation
    [text] => hotel staff
    [match] => 2
    [coll] => 1
)

Array
(
    [id] => 91
    [column_name] => Accommodation
    [text] => marriot
    [match] => 3
    [coll] => 1
)

Tried with following code:

foreach ($result as $key =>$element) {
        if($element['column_name'] == 'Accommodation'){
                echo "<pre>";print_R($element);
            }
        }
OMi Shah
  • 5,768
  • 3
  • 25
  • 34
coder
  • 11
  • 3
  • Does this answer your question? [How to remove duplicate values from a multi-dimensional array in PHP](https://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – OMi Shah Nov 01 '22 at 06:42
  • @OMiShah no because i dont want to "remove" value i just want to "combine/merge" values – coder Nov 01 '22 at 06:44

1 Answers1

0

For each entry generate the key (i'm using zero-characted-joined values), and fill the output array, appending text if entry with such the key already exists:

<?php
$input = [
    [
        'id' => 86,
        'column_name' => 'Accommodation',
        'text' => 'hotel',
        'match' => 2,
        'coll' => 1,
    ],

    [
        'id' => 87,
        'column_name' => 'Accommodation',
        'text' => 'staff',
        'match' => 2,
        'coll' => 1,
    ],
    [
        'id' => 91,
        'column_name' => 'Accommodation',
        'text' => 'marriot',
        'match' => 3,
        'coll' => 1,
    ],
];

$output = [];
foreach( $input as $entry ){
    $key = implode("\0",[$entry['column_name'],$entry['match'],$entry['coll']]);

    // No such entry yet
    if( empty( $output[$key] ) )
        $output[ $key ] = $entry;
    // This is a duplicate, appending text
    else
        $output[ $key ]['text'] .= ' ' . $entry['text'];
}

print_r( array_values($output) );

Jared
  • 1,294
  • 2
  • 8
  • 13