简体   繁体   English

根据php中的键对数组值进行分组?

[英]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?请注意,作者的值相对于主键“No”进行了合并。有人可以帮我解决这个问题吗?

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']];
    }
}

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的结构如下,这应该可以为您提供所需的输出。

$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.在开发过程中,您可以配置 php.ini,也可以在 php 脚本的开头插入此代码。 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:感谢crafter 提供了很棒的功能,如果有人需要为多个键分组,我将crafter 功能编辑为:

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;
}

Thanks to crater and Fabio's answer.感谢火山口和法比奥的回答。 I updated the code to check if the size of the key is not greater than one (1), underscore will not be appended.我更新了代码以检查密钥的大小是否不大于一 (1),不会附加下划线。

function _group_by($array, $keys=array()) {
    $return = array();
    $append = (sizeof($keys) > 1 ? "_" : null);
    foreach($array as $val){
        $final_key = "";
        foreach($keys as $theKey){
            $final_key .= $val[$theKey] . $append;
        }
        $return[$final_key][] = $val;
    }
    return $return;
}

I have wrote an another version of Crafter's answer which is remove given key from actual array.我写了另一个版本的 Crafter 答案,它从实际数组中删除了给定的键。 May help someone.可能会帮助某人。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM