将新数据附加到多维数组

时间:2013-05-04 00:04:46

标签: php arrays multidimensional-array

请帮帮我。我想将新数据附加到多维数组,但结构与原始结构相同。这就是我现在所拥有的:

<?php
session_start();
$ses = session_id();
if (isset($_POST['title'])){
if(!empty($_SESSION[$ses])){
    $title = $_POST['title'];
    array_push($_SESSION[$ses], $title);
    array_push($_SESSION[$ses], $_POST['desc']);
}else{
    $title = $_POST['title'];
    $_SESSION[$ses] = array(array($title, $_POST['desc']));
}
}
?>

现在输出如下:

Array
    (
    [0] => Array
                (
        [0] => 1
        [1] => 2
                )

        [1] => 3
        [2] => 4
)

但是我希望3和4像这样添加:

Array
    (
    [0] => Array
                (
        [0] => 1
        [1] => 2
                )
    [1] => Array
               (
        [1] => 3
        [2] => 4
      )
)

如何修改我的代码来实现这一目标?我真的被卡住了,请帮忙!!!

2 个答案:

答案 0 :(得分:1)

您将每个值,标题和描述作为单独的对象推送到数组中。实例化一个额外的数组,设置该对象中的标题和描述,并将该数组推送到您的父对象上。

<?php
session_start();
$ses = session_id();
if (isset($_POST['title'])){
    if(!empty($_SESSION[$ses])){
        array_push($_SESSION[$ses], array($_POST['title'], $_POST['desc']));
    }else{
        $title = $_POST['title'];
        $_SESSION[$ses] = array(array($title, $_POST['desc'])); // <--- As you had done     here
}

} ?&GT;

答案 1 :(得分:0)

这一定就足够了:

session_start();
$ses = session_id();
if (isset($_POST['title'])){
    $_SESSION[$ses][] = array($_POST['title'], $_POST['desc']);
}