phparrayscombiners

Compare values and combine


How can I combine the text values of the same pr value?

Array ( 
[0] => Array ( [ID] => 1 [text] => text1 [pr] => project1) 
[1] => Array ( [ID] => 2 [text] => text2 [pr] => project1)
[2] => Array ( [ID] => 2 [text] => text3 [pr] => project2)
[3] => Array ( [ID] => 2 [text] => text4 [pr] => project2)
[4] => Array ( [ID] => 2 [text] => text5 [pr] => project1)
)

Output:

$newarray = array(
        "project1" => "text1 | text2 | text5",
        "project2" => "text3 | text4",
    );

Solution

  • I would do it this way:

    <?php
    
    $array = Array(
        0 => Array('ID' => 1, 'text' => 'text1', 'pr' => 'project1'),
        1 => Array('ID' => 2, 'text' => 'text2', 'pr' => 'project1'),
        2 => Array('ID' => 2, 'text' => 'text3', 'pr' => 'project2'),
        3 => Array('ID' => 2, 'text' => 'text4', 'pr' => 'project2'),
        4 => Array('ID' => 2, 'text' => 'text5', 'pr' => 'project1'),
    );
    
    
    $newArray = [];
    
    foreach ($array as $item) {
        $newArray[$item['pr']][] = $item['text'];
    }
    
    foreach ($newArray as $k => $v) {
        $newArray[$k] = implode(' | ', $v);
    }
    
    
    var_dump($newArray);
    

    Output:

    array(2) { ["project1"]=> string(21) "text1 | text2 | text5" ["project2"]=> string(13) "text3 | text4" }