Group array values based on key in php?

Aditya picture Aditya · Jan 1, 2013 · Viewed 55.3k times · Source

I have a array like this:

$str=
   Array
(
    [No] => 101
    [Paper_id] => WE3P-1
    [Title] => "a1"
    [Author] => ABC
    [Aff_list] => "University of South Florida, Tampa, United States"
    [Abstracts] => "SLA"

)

Array
(
    [No] => 101
    [Paper_id] => WE3P-1
    [Title] => "a2"
    [Author] => DEF
    [Aff_list] => "University of South Florida, Tampa, United States"
    [Abstracts] => "SLA "

)

Array
(
    [No] => 104
    [Paper_id] => TU5A-3
    [Title] => "a3"
    [Author] => GHI
    [Aff_list] => "University of Alcala, Alcala de Henares, Spain"
    [Abstracts] => "Microwave"

)

I want to group elements in the array based upon 'No' as primary key. The output should look like this:

 array(6) {
  ["No"]=>
  string(6) "101"
  ["Paper_id"]=>
  string(6) "WE3P-1"
  ["Title"]=>
  string(80) ""a-1"
  ["Author"]=>
  string(14) "ABC"
  ["Aff_list"]=>
  string(51) ""University of South Florida, Tampa, United States""
  ["Abstracts"]=>
  string(5) ""(SLA)"
"
}
array(6) {
  ["No"]=>
  string(3) "104"
  ["Paper_id"]=>
  string(6) "TU5A-3"
  ["Title"]=>
  string(40) "a2"
  ["Author"]=>
  string(20) "DEF"
  ["Aff_list"]=>
  string(48) ""University of Alcala, Alcala de Henares, Spain""
  ["Abstracts"]=>
  string(9) ""Microwave"
"
}

Note that the Author's value got merged with respect to the primary key 'No'.Can anyone help me out from this, please?

I tried doing this:

foreach($paper_info as $element) {
    foreach($element as $v) {
        $id = $element['No'];
        if (!isset($out[$id])) {
            $out[$id] = [
                'No' => $element['No'],
                'Paper_id' => $element['Paper_id'],
                'Title' => $element['Title'],
                'Authors' => [],
                'Aff_list' => $element['Aff_list'],
                'Abstracts' => $element['Abstracts']
            ];
        }
        $out[$id]['Authors'][] = ['Authors' => $element['Author']];
    }
}

Answer

crafter picture crafter · Feb 27, 2013

You could use a generic function:

function _group_by($array, $key) {
    $return = array();
    foreach($array as $val) {
        $return[$val[$key]][] = $val;
    }
    return $return;
}

I added some sample code to test

<?php

$list= [
[   'No' => 101,
    'Paper_id' => 'WE3P-1',
    'Title' => "a1",
    'Author' => 'ABC',
    'Aff_list' => "University of South Florida, Tampa, United States",
    'Abstracts' => "SLA"
] ,
[   'No' => 101,
    'Paper_id' => 'WE3P-1',
    'Title' => "a2",
    'Author' => 'DEF',
    'Aff_list' => "University of South Florida, Tampa, United States",
    'Abstracts' => "SLA"
] ,
[    'No' => 104, 
    'Paper_id' => 'TUSA-3',
    'Title' => "a3",
    'Author' => 'GH1',
    'Aff_list' => "University of Alcala, Alcala de Henares, Spain",
    'Abstracts' => "Microwave"
] ];

print_r(_group_by($list, 'No'));