Add data in Session array

Asked

Viewed 64 times

0

I am using PHP to develop an application and I am using the following code to keep information in a session and return the data to generate an alert for the user:

class Data{
    const DATA = "DATA";

    public static function setData($type, $data){
        $_SESSION[Data::DATA] = array($type=>$data);
    }

    public static function getData(){
        $data = (isset($_SESSION[Data::DATA]) && $_SESSION[Data::DATA]) ? $_SESSION[Data::DATA] : '';
        Data::clearData();
        return $data;
    }

    public static function clearData(){
        $_SESSION[Data::DATA] = NULL;
    }
}

On one of my routes, then, I play the information I need in the session using the following code:

Data::setData(['01' => 'aviso 01', '02' => 'aviso 02']);

Only, on this same route and at another time, I need to call the setData again and put more information in the session:

Data::setData(['03' => 'aviso 03', '04' => 'aviso 04']);

The problem is that when I call the method again, the first information is lost, being kept only the last information that was sent to the session.

I would like to know what I need to do to keep all the data in the session, how to add new elements in the session array and how to call this information.

Can you help me? Thank you very much!!!

Thank you very much!

1 answer

1


If that’s what I understand, I’d just use the array_merge, something like:

public static function setData($type, $data){

    r = array($type=>$data);

    if (!empty($_SESSION[Data::DATA])) {
        r = array_merge($_SESSION[Data::DATA], r);
    }

    $_SESSION[Data::DATA] = r;
}

That way if there is a value it will match the value with the new one. Maybe you can reduce the code to:

public static function setData($type, $data){
    $_SESSION[Data::DATA] = array_merge((array)$_SESSION[Data::DATA], array($type=>$data));
}

This does the same as the first case, but more gambiarrento, since it converts the session value to an array (even an null), lest bug the array_merge, but...

  • After breaking your head until you almost eat a piece of wall, you don’t realize how simple a solution can be. That’s exactly what I should have done to you. It helped me immensely! Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.