将多列合并为一个数组,作为结果集中的关键之一

时间:2019-03-25 00:42:12

标签: php arrays json

我无法将数据放入正确的结构中。我的结果集数据为:

array (
  0 => 
  array (
    'company_id' => 1,
    'company_abbrev' => 'amd',
    'description' => 'amd blah blah blah 1',
  ),
  1 => 
  array (
    'company_id' => 1,
    'company_abbrev' => 'amd',
    'description' => 'amd blah blah blah 2',
  ),
  2 => 
  array (
    'company_id' => 2,
    'company_abbrev' => 'int',
    'description' => 'int blah blah 1',
  ),
  3 => 
  array (
    'company_id' => 2,
    'company_abbrev' => 'int',
    'description' => 'int blah blah 2',
  ),

我正在尝试将描述合并成每个公司内唯一的,唯一的条目中的数组:

array (
  'amd' => 
  array (
    'company_id' => 1,
    'job_description' => 
    array (
      0 => 'amd blah blah 1',
      1 => 'amd blah blah 2',
    ),
  ),

我所遇到的循环是在到达最后一家公司时,将每个不同公司的所有职位描述堆积在一起。我在做什么错了?

for($i = 0; $i < sizeof($comp); $i++) {
            $companies[$comp[$i]['company_abbrev']] = $comp[$i];
            $array[] = $comp[$i]['description'];
            $companies[$comp[$i]['company_abbrev']]['job_description'] = $array;
}

2 个答案:

答案 0 :(得分:0)

foreach($comp as $com) {
    if(!isset($companies[$com['company_abbrev']])) {
        $companies[$com['company_abbrev']] = array();
        $companies[$com['company_abbrev']]['company_id'] = $com['company_id'];
    }

    $companies[$com['company_abbrev']]['description'][] = $com['description'];
}

此循环使用公司缩写将其分组

答案 1 :(得分:0)

您可以像下面这样遍历数组,

$res = [];
array_walk($arr, function (&$val, $key) use (&$res) {
    $res[$val['company_abbrev']]['company_id']        = $val['company_id']; // setting company id
    $res[$val['company_abbrev']]['job_description'][] = $val['description']; // AUTOMATIC mapping
});
print_r($res);

输出

Array
(
    [amd] => Array
        (
            [company_id] => 1
            [job_description] => Array
                (
                    [0] => amd blah blah blah 1
                    [1] => amd blah blah blah 2
                )

        )

    [int] => Array
        (
            [company_id] => 2
            [job_description] => Array
                (
                    [0] => int blah blah 1
                    [1] => int blah blah 2
                )

        )

)

Demo)。