phparraysconcatenationgroupingprefix

Group values of a 1d array by prefix and concatenate suffixes in each group


I have a flat, indexed array supplied by user input. I need to consolidate values which have the same value before the pipe. When a prefix is encountered after the first time, the new value's suffix should be appended to the earlier value and separated by a comma.

Array
(
    [0] => 1|1
    [1] => 1|2
    [2] => 1|3
    [3] => 1|4
    [4] => 1|5
    [5] => 1|6
    [6] => 1|32
    [7] => 1|35
    [8] => 2|1
    [9] => 2|5
    [10] => 3|1
    [11] => 3|8
    [12] => 3|11
    [13] => 3|13
    [14] => 3|35
)

Desired result:

Array
(
    [0] => 1|1,2,3,4,5,6,32,35
    [1] => 2|1,5
    [2] => 3|1,8,11,13,25
)

Solution

  • Loop through your $_POST and explode using the | delimiter

    $array = array('1|1','1|2','2|1','2|5','3|1','3|8');
    //simplified version of your array
    
    $new_array = array();
    //define a new array  that will be built in the loop below in your desired format
    
    foreach($array as $item){ //loop through original array
    
        $parsed_item = explode('|',$item); 
       //explode each item to split elements using the | as delimiter
    
        if(isset($new_array[$parsed_item[0]])){
             //if $new_array with the current key already exists add new value to existing array (concatenate with a comma to existing value)
            $new_array[$parsed_item[0]] = $new_array[$parsed_item[0]].','.$parsed_item[1];
    
        }else{ 
            //else create new value on array
            $new_array[$parsed_item[0]] = $parsed_item[0].'|'.$parsed_item[1];
        }
    }