Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group array values based on key in php?

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']];
    }
}
like image 610
Aditya Avatar asked Jan 01 '13 18:01

Aditya


People also ask

How do you group data in an array?

Steps to create the groupBy function, create an object as initial value for our result object. inside the array reduce, create an array for each distinct key value and push the currentValue if the key value present in the currentValue.

How to group by and SUM in PHP?

The SUM() is an aggregate function used by the GROUP BY statement. The GROUP BY and SUM operations can be integrated into the data list at the code level in PHP. Use the PHP array_reduce() function to GROUP BY and SUM values of an array in PHP.


2 Answers

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'));
like image 198
crafter Avatar answered Oct 01 '22 01:10

crafter


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');
like image 21
Levi Avatar answered Oct 01 '22 00:10

Levi