how to acces values from array in laravel - php

This is my addToCart method in which I am adding the courses to user_cart column in users table.
public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('id' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['id'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('id' => $course->id));
}
}
$data['id'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
return redirect()->back();
}
And this is my showcart method in which I am taking the courses from users table user_cart column array.
public function showcart(){
$user = Auth::user();
$array = $user->user_cart;
print_r($array);
return view('frontend.my_cart', compact('academic','nonacademic','instructor','coc','my_cart'));
}
And when I am displaying it I am getting the output as follows:
[{"id":84},{"id":86}]
Now can you tell me that how to loop them so I can get the courses? I tried by using a foreach loop for $array but it shows me the error of invalid argument supplied for foreach()

Looks like you are building the array into a JSON or string field within your database on the User object. The resulting array appears to be stored as a JSON string, so decode and then loop:
$array = json_decode( $user->user_cart, true );
foreach($array as $key => $val){
dump $key;
dump $val;
}

Related

Yii2 multiple models loop save error

I've a table in which I have to save multiple data, in my controller I've implemented this action:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
The data received are right but not the result, the only thing that the action do is to add new table row with slider_id and image_id equal to NULL, why the model doesn't save correctly?
Thanks
The thing is when you call
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
you don't change the $model object itself. Essentially you are calling:
SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
So, later when you call $model->save() you are saving a $model object with empty attributes (you only changed display_order)
My advise here: try to assign the result of the ->all() call to the new var and then work with it:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
$models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
if (count($models)) {
// loop through $models and update them
}
}
}
return $result;

PHP - Find Specific Value in Array (multidimensional)

I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?

How to make first array value to uppercase

I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);
but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )
And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
Main MY_Model method
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);
If Its not, then $data array have only read attribute.
The array_from_post() method returns an array with the format below:
$data = array(
'position' => 'it',
'label' => 'Information Technology'
);
So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
static $i = 0;
if ($i === 0) { $i++; return strtoupper($a); }
else return $a;
}, $array);
Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
static $i = 0;
if ($i == 0) { $i++; $value = strtoupper($value); }
});
Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.

dynamic variables from array

I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.

What is wrong with this PHP code?

I have two database tables, one for allowances and one for deductions. I want to calculate net salaries.
I'm using CodeIgniter. Here's my current code:
function get_allowances($eid)
{
$this->db->from('allowances');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('allowances');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
function get_deductions($eid)
{
$this->db->from('deductions');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('deductions');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
and in controller,
function net_salary($eid)
{
$allownces[] = $this->Salary->get_allowances($eid);
$deductions[] = $this->Salary->get_deductions($eid);
return $net_salary = array_sum($allownces) - array_sum($deductions);
}
My net_salary() function gives me a result of 0. What am I doing wrong, and how can I fix it?
Your models with plural names are only going to return a single object.
so what you are ending up with is...
Array
(
[0] => allowance_object
)
and
Array
(
[0] => deduction_object
)
While we really need the schema of your database try this (and make same edits for deductions)...
function get_allowances($eid)
{
$this->db->from('allowances');
$this->db->where('eid',$eid);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row_array(); //<--- return an Array
}
else
{
// make an array instead of object
$salary_obj = array();
//Get all the fields from items table
$fields = $this->db->list_fields('allowances');
foreach ($fields as $field)
{
$salary_array[$field] = 0; //<---- add array keys and set to integer 0 instead of empty string.
}
return $salary_array;
}
}
then in your net_salary function
function net_salary($eid)
{
$allownce = $this->Salary->get_allowances($eid);
$deduction = $this->Salary->get_deductions($eid);
return array_sum($allownce) - array_sum($deduction);
}
Try something like this:
function get_values($eid, $table_name)
{
$this->db->where('eid',$eid);
$query = $this->db->get($table_name);
$salary_obj = $query->result();
$values = array();
foreach($salary_obj as $row){
$values[] = $row->value_column_name;
}
return $values;
}
where value_column_name is the name of the table column (filedname) where the desired value stands.
call in controller:
function net_salary($eid)
{
$allownces = $this->Salary->get_values($eid, 'allowances');
$deductions = $this->Salary->get_values($eid, 'deductions');
return $net_salary = array_sum($allownces) - array_sum($deductions);
}

Categories