Group array values based on key in php? Group array values based on key in php? arrays arrays

Group array values based on key in php?


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


The data format in your question is ambiguous, but assuming the structure for $paper_info is what is below, this should get you the output you're looking for.

$paper_info = array(    array(        'No' => "101",        'Paper_id' => "WE3P-1",        'Title' =>"An Electrically-Small, 3-D Cube Antenna Fabricated with Additive Manufacturing",        'Author' => "Ibrahim Nassar",        ...    ),    array(        'No' => "101",        ...        'Author' => "Thomas Weller",        ...    ));$out = array();foreach($paper_info as $paper) {    $id = $paper['No'];    if (!isset($out[$id])) {        $out[$id] = $paper;        $out[$id]['Author'] = array();    }    $out[$id]['Author'][] = $paper['Author'];}

You should also turn on warnings and display errors in your development environment. I have a feeling it will help you. During development you can either configure your php.ini, or insert this code at the beginning of your php script. Just make sure you remove it before pushing to production.

error_reporting(E_ALL);ini_set('display_errors', '1');


Thanks to crafter for the awesome function, if someone need to group for multiple keys i edited the crafter function to this:

function _group_by($array, $keys=array()) {    $return = array();    foreach($array as $val){        $final_key = "";        foreach($keys as $theKey){            $final_key .= $val[$theKey] . "_";        }        $return[$final_key][] = $val;    }   return $return;}