计算数组中的重复值并连接它们?

时间:2014-04-16 11:43:55

标签: php arrays

Array
(
    [0] => Array
        (
            [title] => test1
            [checkdata] => This is example1
        )

    [1] => Array
        (
            [title] => test1
            [checkdata] => This is example2
        )

    [2] => Array
        (
            [title] => test1
            [checkdata] => This is example3
        )

    [3] => Array
        (
            [title] => test2
            [checkdata] => This is example4
        )

    [4] => Array
        (
            [title] => test3
            [checkdata] => This is example5
        )

这是我的阵列。我想这样做:

Array
(
   [0] => Array
    (
        [title] => test1
        [checkdata] => array(
           [0]=>This is example1
           [1]=>This is example2
           [3]=>This is example3
        )
     )


   [1] => Array
    (
        [title] => test2
        [checkdata] => array(
           [0]=>This is example4
           [1]=>This is example5

        )
     )    

)

感谢。

3 个答案:

答案 0 :(得分:0)

使用嵌套循环的简单方法:

Codepad demo

$result = array();

foreach($arr as $val){
    $found = false;
    foreach($result as $key => $r){
        if($r['title'] == $val['title']){
            $result[$key]['checkdata'][] = $val['checkdata'];
            $found = true;
            break;
        }
    }
    if(!$found){
        $result[] = array(
            'title' => $val['title'],
            'checkdata' => array($val['checkdata'])
        );
    }
}

答案 1 :(得分:0)

如果要按公共键值连接两个(子)数组,可以使用array_merge_recursive

http://php.net/array_merge_recursive

$arr1['checkdata'] = 'This is example4';

$arr2['checkdata'] = 'This is example5';

$merged = array_merge_recursive ($arr1, $arr2); 

返回:

数组([checkdata] =>数组([0] =>这是example4 [1] =>这是example5))

答案 2 :(得分:0)

这应该有效:

<?php
$foo = array(
  array(
    'title' => 'test1',
    'checkdata' => 'This is example1'
  ), array(
    'title' => 'test1',
    'checkdata' => 'This is example2'
  ),
  array(
    'title' => 'test1',
    'checkdata' => 'This is example3'
  ),
  array(
    'title' => 'test2',
    'checkdata' => 'This is example4'
  ),
  array(
    'title' => 'test3',
    'checkdata' => 'This is example5'
  ),
);

$out = [];

foreach ($foo as $value) {
    if (!isset($out[$value['title']])) {
        $out[$value['title']] = [
            'title' => $value['title'],
            'checkdata' => []
        ];
    }
    $out[$value['title']]['checkdata'][] = $value['checkdata'];
}

var_dump($out);