two dimension session issue with codeigniter - php

I want to store two dimensional array in session, where i keep creating the array through a function call.
I am trying with this code
function nextQuestion($questionId,$response)
{
$this->session->set_userdata("res[$questionId][]"),$response);
}
but this is not creating a two dimensional array

The key stored in the session must be a string but the value can be a multi dimensional array.
You can retrieve the array, manipulate it and save it in the session again like this:
$session_response = $this->session->userdata("res");
//some manipulation on $session_response
$this->session->set_userdata('res', $session_response);

sametimes codeigniter session library can be boring.
if i add array to session, i serialize the array.
You can serialize array and get back with unserialize. or you can use php session library.

Related

Why does Laravel store two different array syntaxes in databases and which one is correct?

I come from a Javascript and Ruby background and this is baffling me. Laravel can store two different array syntaxes in my DB depending on how I handle my array serialization. In my understanding, collect() creates a true Laravel array. Why then is it storing a serialized array? Furthermore, is the {'key':'value'}syntax still an array despite having no square brackets surrounding it? It looks to me like a standard object or a hash, but if I try to do toArray() on it, it recognizes that it's already an array and throws an error. What am I misunderstanding and what is correct here?
Given a form:
edit.blade:
<select class="form-control m-bootstrap-select m_selectpicker" name="temp">
<option value={{ json_encode(array("$key"=>"$cph"), JSON_FORCE_OBJECT) }}>
</select>
The following two controllers syntaxes yield different database insertions.
PageController.php:
$page->cph_default = collect($request->temp);
$page->save();
Laravel stores an array with the following syntax in my database: ["{\"11\":\"1100\"}"]
PageController.php
$page->cph_default = json_decode($request->temp, true);
$page->save();
Laravel stores an array with the following syntax in my database: {"19": "1900"}
A PHP array with the syntax ['key' => 'value'] is called an associative array, and acts like a hash. A JSON-encoded associative array will show up as an object in JSON syntax. Examples and more info on PHP.net
Laravel's collect() function is a convenience wrapper for creating a new Collection. A Collection is not really a "true Laravel array" so much as it is an object wrapper with some convenience methods for modifying the underlying array. Think of it like a scalar object.
In your form when generating the option value, the submitted form value ($request->temp) will be a JSON-encoded string. Literally the string '{"19": "1900"}'.
Calling collect($request->temp) does no modification to that submitted data. It's simply creating a new Collection (array), containing a single string item. If you were to call toArray() on the collection, you'd see something like this:
[
0 => '{"19": "1900"}'
]
Note that this is not an associative array, it is a numeric array with a zero-based index. This array is encoded as a JSON array, not as a hash object. Hence your first result.
Calling json_decode($request->temp) is turning the string back into an associative array (hash) before saving it via Eloquent. Eloquent then calls json_encode() again internally, turning it back into the same JSON as your form's option value.
If you were to decode the form value before creating the collection, the resulting database save would look identical. You'd just have the convenience of the Collection wrapper:
$page->cph_default = collect(json_decode($request->temp, true));
$page->save();
If you're treating the column as a JSON type, you should ensure the data passed to Eloquent is NOT already encoded, or you'll get the double encoding experienced in your first example.
No Matter What is.
First If you are stroring the array into database convert to JSON FORMAT
For eg
$variable = json_encode($request->controlname);
This is the right way to store array
Into database

How to retrieve an element from this PHP array?

So basically I have this array stored in SQL and I'm trying to retrieve the first element from it using PHP
I'm not sure if this is an associative or multidimensional array
a:3:{i:0;s:11:"Downpayment";i:1;s:28:"Variable 1 ";i:2;s:28:"Variable 2";}
How do I extract elements from this array ?
This is a PHP representation of serialized data. Use unserialize() on it.
If you not sure in this array you can use current() function or foreach to get first element of this array
For set inner pointer on first element use reset()

Codeigniter accessing array values

I simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.
$plat_options = $this->db->get('tblplatform_options')->select('name')->result();
How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?
In PHP/Codeigniter, can be done in the same way:
$plat_options[0] //if you have this element, usually is better to check if exists.
You can retrieve all the elements with foreach($plat_options as $option){...}
You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/
Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html
I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.
You can use the result_array() function:
$data = $plat_options->result_array();
echo($data[0]['name']);
or:
$data = array_shift($q->result_array());
echo($data['name']);
I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.
If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.
Hope it helps!

PHP Specific Array Organization Function

I have a few session arrays which I happen to be removing specific indexes from. For example, I have a session named $_SESSION['products'], this session has these elements: $_SESSION['products'][0], $_SESSION['products'][1], and $_SESSION['products'][2].
I am trying to remove any one of those variables, the problem is when you remove the second variable, you mess up the array so that it cannot be displayed in a for loop. Is there a way to rearrange the following: $_SESSION['products'][0] and $_SESSION['products'][2] to $_SESSION['products'][0] and $_SESSION['products'][1] with a PHP built-in function? If not, is it even possible?
You can achieve this with array_values like:
unset($_SESSION['products'][2]); // assuming the product key
// exist in product array sess
$_SESSION['products'] = array_values($_SESSION['products']);
Manual
array_values() returns all the values from the array and **indexes the array numerically.**

Can we do like this using PHP SESSION array?

Hi can we create two dimensional array using php session. If possible how to unset values randomly.
No, PHP does not implement multi-dimensional arrays. However an element of an array can be an array itself. And any PHP data item can be stored in the session (however resources become meaningless outisde the thread they were initialized in, and objects require class definitions to be referenced from the session).
e.g.
<?php
$two_d=array(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array('#','.','=')
);
$two_d[3][2]='*'; // was '='
how to unset values randomly
This would be an oxymoron in a 2-dimensional array. But is perfectly valid in the context of an array of arrays:
unset($two_d[1]); // removed the whole second row from the above
unset($two_d[0][1]); // $two_d[0] is now array(1,3)
$_SESSION['whateverValue'] = Array(
1 => Array (
'a','b','c','d'
),
2 => Array (
'q','w','e','r','t'
)
);
Voila, a two-dimensional array, in a session.
The session variables are in no way special while the script is executing. Their only "magic" is that they are unserialized at session_start() and serialized at session_close()

Categories