How to set an array in session in codeigniter? - php

I am little bit struggling in setting array in session.
Here is my code:-
Controller:
function taketest(){
$this->load->model('', '');
$questions_for_test = $this->session->userdata('questions_for_test');
$difficulty_level = $this->session->userdata('difficulty_level');
$question_id = $this->session->userdata('question_id');
if($question_id==""){
$question_id = $this->myjcat->returnRandomQuestion($questions_for_test,$difficulty_level);
$this->session->set_userdata('question_id',$question_id);
}
$question_details = $this->myjcat->getQuestion($question_id);
}
Model:
function returnRandomQuestion($questions_for_test, $difficulty_level){
$question_id = array_rand($questions_for_test[$difficulty_level], 1);
$used_question=array();
$used_questions=$questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);
return $questions_for_test[$difficulty_level][$question_id];
}
But when I call:
$used_questions = $this->session->userdata('used_questions');
in controller
in the controller it will not return me an array.It gives me last value stored in it.

I could be misreading things, but it looks like you are only storing one value.
// this code:
$used_questions=$questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);
// is the same as this code
$this->session->set_userdata('used_questions',$questions_for_test[$difficulty_level][$question_id]);
You're probably looking for this:
// fetch the stored copy first.
$used_questions = $this->session->userdata('used_questions');
if(!is_array($used_questions)) $used_questions = array();
// note the []
$used_questions[] = $questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);

You can set array values in session data like this :-
$this->session->set_userdata('used_questions', json_encode($used_questions));
And retrieve the data as :-
json_decode($this->session->userdata('used_questions'));
If you want the retrieved array data as associative array :-
json_decode($this->session->userdata('used_questions'), true);
Hope it hepls you :)

The problem is that $used_questions is storing the value stored in $questions_for_test[$difficulty_level][$question_id] and not the array.
So do this $this->session->set_userdata('used_questions',$questions_for_test);

This is because the data you pass to the $used_questions is a value.
You might want to do something like this:
array_push($used_questions, $questions_for_test[$difficulty_level][$question_id]);
*appending / adding a new value to an array

Related

Php access variable

In PHP i have array variable from another function like this
$v->params:
(
[{"username":"myusername","email":"myemail#gmail_com","phone":"0123456789","password":"abc123","fullname":"myfullname","register_ip":"127_0_0_1","country":"Qu\u1ed1c_Gia","birthday":"N\u0103m_sinh","gender":"male","bank_code":"Ng\u00e2n_h\u00e0ng","ip":"127_0_0_1","os":"Windows_10","device":"Computer","browser":"Mozilla_Firefox_77_0"}] =>
)
Now i want to access to it item, how can i code to access item value like this:
$password = $v->params->password; //myemail#gmail_com
I new with PHP thank you all
The data seems the wrong way round as it's the key of the array rather than a value.
So using array_keys()[0] to get the first key and then json_decode this...
$data = json_decode(array_keys($v->params)[0]);
you can then use the $data object to get at the values...
echo $data->username;

How to retrieve data from a database as an array in Laravel?

Normally data retrieved as an object from database in Laravel when we use get() function. But I want to retrieved data as an array.
In CodeIgnitor we use get_array(). What we use in Laravel ?
I have already tried with toArray(). But no result.
$doctor_result = Doctor::select('*')->toArray();
How to solve that?
I got result. just change the code
$doctor_result = Doctor::all()->toArray();
You can also do like this.
$result = DB::table('tableName')->get();
$resultArray = $result->toArray();
second way, but some tricky.
$resultArray = json_decode(json_encode($result), true);

Passing a dynamic variable in an array within PHP

I am not sure if it's possible or not but I am trying to pass a random variable to fill an array.
Here is the code normally:-
//Loading all data of user in an array variable.
$user_fields = user_load($user->uid);
// Updated one array variable in this array.
$user_fields -> field_module_3_status['und'][0]['value'] = "Started";
// Saved back the updated user data
user_save($user_fields);
But I want to provide the variable field_module_3_status dynamically through a variable.
Hence suppose I have $user_field_name = field_module_3_status.
So what I tried to do is:-
$user_fields = user_load($user->uid);
$this_users_status = $user_fields -> $user_field_name;
$this_users_status['und'][0]['value'] = "Started";
user_save($user_fields);
Unfortunately this doesn't work.
Any idea how I can achieve this?
You're making a copy of the array when you do the assignment to $this_users_status. You need to assign to the array in the object property.
$user_fields->{$user_field_name}['und'][0]['value'] = "Started";
Or you could use a reference:
$this_users_status =& $user_fields->$user_field_name;

store array in the database

I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Categories