如何使数组成为子数组?

时间:2014-05-14 09:46:49

标签: php arrays

我正在使用一个数组,我已经得到了答案,但我需要为我的数组添加1个数组层。以下是我的例子:

这是我的阵列:

$newOptions = array();
    foreach ($community_comment as $option) {
        $date = $option['date'];
        $text = $option['text'];

        $newOptions[$date][] = $text;
    }

这是我的结果:

Array
(
    [2014-05-14] => Array
        (
            [0] => test test test test
            [1] => test2
        )

)

但我希望我的结果是这样的:

Array
    (
       [0]=>Array(
            [2014-05-14] => Array
            (
                [0] => test test test test
                [1] => test2
            )
    )
    )

希望我能得到一些帮助。谢谢你提前。

5 个答案:

答案 0 :(得分:0)

这应该适合你:

$newOptions = array();
foreach ($community_comment as $option) {
    $date = $option['date'];
    $text = $option['text'];

    $newOptions[][$date][] = $text;
}

答案 1 :(得分:0)

你只需要改变
$newOptions[$date][] = $text;

$newOptions[][$date][] = $text;

答案 2 :(得分:0)

$i = 0;
$fake_array = array();
foreach ($community_comment as $option) {
    $date = $option['date'];
    $text = $option['text'];

    if(isset($fake_array[$date])) {
        $newOptions[$fake_array[$date]][$date][] = $text; // $fake_array[$date] = old index
    }
    else {
         $newOptions[$i][$date][] = $text;
         $fake_array[$date] = $i;
    }
    $i++;
}

答案 3 :(得分:0)

$newOptions = array();
    foreach ($community_comment as $option) {
        $date = $option['date'];
        $text = $option['text'];

        $newOptions[][$date][] = $text;
    }

答案 4 :(得分:0)

我找到了答案,这个答案适合在我的项目中实施。

foreach ($community_comment as $option) {
        $date = $option['date'];
        $text = $option['text'];
        $id = $option['id'];

        $data['text'] = $text;
        $data['id'] = $id;
        $newOptions[$date][] = $data;
    }

    $result = array();
    foreach ($newOptions as $key=>$value)
    {
        $result['date'] = $key;
        $result['data'] = $value;

        $result2[]=$result;
    }