1

please help me out. I want to append new data to a multidimensional array but structure it the same way the original was structured. Here's what I have right now:

<?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']));
}
}
?>

Right now the output looks like this:

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

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

But I want the 3 and 4 to be appended like this:

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

How can I modify my code to achieve that? I'm really stuck, please help!!!

2 Answers 2

1

You're pushing each value, the title and the description into the array as separate objects. Instantiate an additional array setting the title and description in that object, and push that array onto your parent.

<?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
}

} ?>

Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm!!! I swear I thought I tried every possible combination!!! I just couldn't find an example that did that. Thank you soooo much!
As Casimir pointed out, the if(!empty()) call accomplishes the same thing. If you don't have any other processing you're doing if the Session index is empty, I'd remove it and just make one push call! Cheers and happy coding. :)
0

This must be enough:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.