基于PHP中的关键组数组值? [英] Group array values based on key in php?

查看:141
本文介绍了基于PHP中的关键组数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

$str=
   Array
(
    [No] => 101
    [Paper_id] => WE3P-1
    [Title] => "An Electrically-Small, 3-D Cube Antenna Fabricated with Additive Manufacturing"
    [Author] => Ibrahim Nassar
    [Aff_list] => "University of South Florida, Tampa, United States"
    [Abstracts] => "SLA"

)

Array
(
    [No] => 101
    [Paper_id] => WE3P-1
    [Title] => "An Electrically-Small, 3-D Cube Antenna Fabricated with Additive Manufacturing"
    [Author] => Thomas Weller
    [Aff_list] => "University of South Florida, Tampa, United States"
    [Abstracts] => "SLA "

)

Array
(
    [No] => 104
    [Paper_id] => TU5A-3
    [Title] => Signal-Interference Microstrip Duplexers
    [Author] => Roberto Gomez-Garcia
    [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) ""An Electrically-Small, 3-D Cube Antenna Fabricated with Additive Manufacturing""
  ["Author"]=>
  string(14) "Ibrahim Nassar" , "Thomas Weller"
  ["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) "Signal-Interference Microstrip Duplexers"
  ["Author"]=>
  string(20) "Roberto Gomez-Garcia"
  ["Aff_list"]=>
  string(48) ""University of Alcala, Alcala de Henares, Spain""
  ["Abstracts"]=>
  string(9) ""Microwave"
"
}

需要注意的是作者的价值得到相对于主键合并No'.Can有人帮助我从这个好吗?

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

我试着这样做:

foreach($paper_info as $element) {
    foreach($element as $v) {
        $id = $element['No'];
        if (!isset($out[$id])) {
            out[$id] = array(
                'No'=>$element['No'],
                'Paper_id' => $element['Paper_id'],
                'Title' => $element['Title'],
                'Authors' => array(),
                'Aff_list' => $element['Aff_list'],
                'Abstracts' => $element['Abstracts']
            );
        }
        $out[$id]['Authors'][] = array('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;
}

这篇关于基于PHP中的关键组数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆