Home > Net >  How to combine multi-dimension array values according to same value in PHP
How to combine multi-dimension array values according to same value in PHP

Time:11-01

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);
            }
        }

CodePudding user response:

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) );

  • Related