PHP Multidimension数组删除索引键并组合

时间:2016-03-18 08:18:37

标签: php arrays

我有一个数组如下。我需要没有索引键(0,1,2)的新数组和组合具有重复主题的数组。

Array
(
[0] => Array
    (
        [email] => Array
            (
                [subject] => subjecting
                [to] => testemail@gmail.com
            )

    )

[1] => Array
    (
        [email] => Array
            (
                [subject] => bothsubject
                [to] => textmail@gmail.com
            )

    )

[2] => Array
    (
        [email] => Array
            (
                [subject] => bothsubject
                [to] => textmail11@gmail.com
            )

    )

 )

输出应如下

  [email] => Array
            (
                [subject] => subjecting
                [to] => testemail@gmail.com
            )
            [email] => Array
            (
                [subject] => bothsubject
                [to] =>textmail@gmail.com, textmail11@gmail.com
            )

我已经尝试过array_map函数,foreach循环,遗憾的是不知道如何执行。

1 个答案:

答案 0 :(得分:0)

您可以使用以主题为关键字的中间数组:

$source = array(
    array(
        'email' => array(
            'subject' => "subjecting",
            'to' => 'bharat@intricare.net',
            )
        ),
    array(
        'email' => array(
            'subject' => 'bothsubject',
            'to' => 'textmail@gmail.com'
            )
        ),
    array(
        'email' => array(
            'subject' => 'bothsubject',
            'to' => 'textmail11@gmail.com'
            )
        )
    );

$subjects = array();
foreach ($source as $item) {
    $to = $item['email']['to'];
    $subject = $item['email']['subject'];

    if (isset($subjects[$subject]))
        $to = implode(',', array($subjects[$subject], $to));

    $subjects[$subject] = $to;
}

$result = array();
foreach ($subjects as $subject => $to) {
    $result[] = array(
        'email' => array(
            'subject' => $subject,
            'to' => $to
        )
    );
}

输出:https://eval.in/538532