Having an issue with array keys, undefined index - php

I'm working with a couple of arrays, one of which has keys that are the productid, the value being an object that contains a doctrine entity of that product. Similarly, I have a plan with the index being the plan Id. For this for loop, I need to go through and individually set up invoices for each plan-product pair (the quantity will always be the same between them, except in cases where a user is purchasing a plan for an already owned device). Obviously this is somewhat complicated, so I'm not exactly sure how to phrase this question. An error occurs at the commented line, "Notice: Undefined Index"
for ($i = 0; $i < $totalInvoices; $i++) {
if ($i == $planQuantity[key($plans)]) {
next($plans);
}
if ($i == $productQuantity[key($products)]) {
next($products);
}
$data = array(
'planId' => key($plans),
//below here, I'm thinking at key($products) is where the error occurs
'productId' => key($products) != 0 ? key($products) : $plans[key($plans)]->getPricingTier()->getProductId(),
'userId' => $this->userId,
'paymentMethodId' => $paymentMethodId
);
if ($order['hasProduct'] || isset($order['activating'])) {
if (!isset($order['activating'])) {
$planModel->createDevicePlan($data);
$productAmount = $products[key($products)]->getAmount();
} else {
$data['deviceId'] = $order['activating']['inventoryId'];
$planModel->createDevicePlan($data, date('Y-m-d'));
$productAmount = 0;
}
} else {
$productAmount = 0;
}
if ($iteration % 5 == 0 && $order['hasShipping']) {
$invoiceShippingAmount = $billingModel->getShippingAmount($shippingOptionsId);
} else {
$invoiceShippingAmount = 0;
}
$salesData = array(
'paymentMethodsId' => $paymentMethodId,
'planAmount' => $plans[key($plans)]->getAmount(),
'planId' => key($plans),
'productAmount' => $productAmount,
'productId' => key($products),
'shippingAddressesId' => $shippingAddressId,
'shippingAmount' => $invoiceShippingAmount,
'shippingOptionsId' => $shippingOptionsId,
'transactionId' => $transactionId,
'userId' => $this->userId
);
$iteration++;
$billingModel->createInvoice($salesData);
}
Any help would be greatly appreciated.

Based on your comment reply, I think this will help
$plans_on_invoice = 0;
$products_on_invoice = 0;
for ($i = 0; $i < $totalInvoices; $i++) {
next($plans);
if ($plans_on_invoice == 0) {
$plans_on_invoice = $planQuantity[key($plans)];
}
plans_on_invoice--;
next($products);
if ($products_on_invoice == 0) {
$products_on_invoice = $productQuantity[key($products)];
}
products_on_invoice--;

Related

How to check for a value on a different table?

I have 2 tables one called Exams and the other Exam Results. In the exam I enter the passing_score and in the Exam Results I save the answer of the exam. I'm trying to look up the passing_score and if the passing score is greater then the result then the person passed.
Here is the entire function of this code
public function exam($course_id, Request $request)
{
$course = Course::where('id', $course_id)->firstOrFail();
$answers = [];
$exam_score = 0;
foreach ($request->get('question') as $question_id => $answer_id) {
$question = ExamQuestion::find($question_id);
$correct_answer = ExamOption::where('exam_question_id', $question_id)
->where('id', $answer_id)
->where('is_correct', 1)->count() > 0;
$answers[] = [
'exam_question_id' => $question_id,
'exam_option_id' => $answer_id,
'corect' => $correct_answer
];
if ($correct_answer) {
$exam_score += $question->score;
}
}
$exam_result = ExamResult::create([
'exam_id' => $course->exam->id,
'employee_id' => \Auth::id(),
'result' => $exam_score,
]);
$exam_result->answers()->createMany($answers);
$exam_id = ExamResult::all();
$final_results = Exam::where('id', $exam_id)->get(['passing_grade']);
$val = $final_results->passing_grade;
if($exam_result->result >= $val) {
$exam_result->is_complete = 1;
$exam_result->save();
}
return redirect()->route('learn.show', [$course, $request])->with('message', 'Test score: ' . $exam_score);
}
Here is the logic I've tried and I get stuck.
$exam_id = ExamResult::all();
$final_results = Exam::where('id', $exam_id)->get('passing_grade');
$val = $final_results->passing_grade;
if($exam_result->result >= $val) {
$exam_result->is_complete = 1;
$exam_result->save();
}
Here is the error I'm getting
Argument 1 passed to Illuminate\Database\Grammar::columnize() must be
of the type array, string given, called in
/Applications/MAMP/htdocs/QuickHS/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php
on line 137
Here is the database structure for the 2 tables
This is the exam table
This is the exam results table
Here is the correction. Please try this.
$final_results = Exam::where('id', $exam_id)->first();
$val = $final_results->passing_grade;
I've resolved it and here is how I did it
$final_results= Exam::first();
$x = $final_results->passing_grade;
if($exam_result->result >= $x)
{
$exam_result->is_complete = 1;
$exam_result->save();
}

Check if array exist by two keys with PHP

I'd like to check if array exist by two keys: id and type
This code just check by id:
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else {
$type = '';
}
if (array_key_exists($id, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
I have tried with this code but it doesn't work:
if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
$_SESSION['cart'] is an array contains arrays of $line
$line = array(
'id' => $id,
'type' => $type,
'quantity' => $quantity,
'price' => $price,
'picture' => $dish->getPicture()->getWebPath(),
);
This is the output of $_SESSION['cart']:
As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem
$lineExists = false;
foreach($_SESSION['cart'] as $index => $line){
if($line['id'] === $id)
{
$_SESSION['cart'][$index]['quantity'] += $quantity;
$lineExists = true;
}
}
if(!$lineExists)
{
$_SESSION['cart'][] = $newLine;
}
If you want to check if type and id exists then you should do something like this
if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
// stuff here..
}
if $id is the value of the key id so 'id' => 5 then you should check like this:
if ($_SESSION['cart']['type'] == $id) {
// stuff here
}
Hope this somewhat helps you further!

How to format json to what I need?

ok, Going to get this out of the way right now. I suck at php. I am building an angular app that is going to populate a mobile app with data from the database. I having it pull from the database just fine but I need the json formatted in a special way and I have no idea how to do it.
Using json_encode this is how it is coming from the database:
[
{
"id":"1",
"date":"2014-10-03",
"time":"2014-10-03 10:45:05",
"amount":"5"
},
{
"id":"2",
"date":"2014-10-03",
"time":"2014-10-03 12:21:05",
"amount":"2"
}
]
This is how I need it organized (this is just dummy data im using in on the angular side)
[
{
date: '2014-09-04',
feeding: [
{
id: '1',
time: '1409852728000',
amount: '3'
},
{
id: '2',
time: '1409874328000',
amount: '4'
},
]
},
{
date: '2014-09-05',
feeding: [
{
id: '3',
time: '1409915908000',
amount: '3.5'
},
{
id: '4',
time: '1409957908000',
amount: '5'
},
]
},
]
I needs to be seperated out and grouped by date. How would I go about doing this?
Airtech was just about there. Small update to the function though. The feeding value needs to be an array of objects rather than an object. You then need to push individual objects into that array.
function dateparse($in) {
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2]["feeding"][] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$feeding = array("id" => $in[$i]->id, "time" => $in[$i]->time, "amount" => $in[$i]->amount);
$out[] = array("date" => $in[$i]->date, "feeding" => array($feeding));
}
}
return json_encode($out);
}
How about the following? I tested it on your json input example and it ran fine.
function parse($in)
{
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2][]["feeding"] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$out[] = array("date" => $in[$i]->date, "feeding" => array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount));
}
}
return json_encode($out);
}
How about this ? This works fine and works as expected :) :-
function dateparse($var)
{
$counter=0; $var = json_decode($var); $date=array();
foreach($var as $key=>$value){foreach($value as $val1=>$val2)
{if($val1 == "date")
{foreach($value as $val3=>$val4)
{if($val3!="date") //because we don't want date again
{
$date[$val2]["feeding"][$counter][$val3] = $val4; continue;
}}continue;
}
}$counter++;}
return json_encode($date);}

How to insert multidimentional array to mysql in codeigniter

i have a mysql table with field id,meta_key,meta_value. i want to add multiple metavalue and metakeys when i add any listing, here is my controller code
$listingid=145;
$metakey=array();
$metavalue=array();
if($data['submitlisting'])
{
if($vehicle_make != "")
{
$metakey[]="vehicle_make";
$metavalue[]=$vehicle_make;
}
if($vehicle_mileage != "")
{
$metakey[]="vehicle_mileage";
$metavalue[]=$vehicle_mileage;
}
if($vehicle_year != "")
{
$metakey[]="vehicle_year";
$metavalue[]=$vehicle_year;
}
$data['listingmeta']=$this->Classifieds_model->addmeta($listingid,$metakey,$metavalue,$data);
here is the model code
function addmeta($listingid,$metakey,$metavalue,$data2)
{
$this->load->database();
$data = array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
);
foreach($data2['listingmeta'] as $meta)
$this->db->insert('classifieds_meta',
array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
)
);
}
but the above code doesnt work, please can someone help?
The propest way, it's better to avoid SQL commands in loops :
$insert_batch = array();
for($i=0; $i<count($); $i++)
{
$insert['classifieds_id'] = $listingid;
$insert['meta_key'] = $metakey[$i];
$insert['meta_value'] = $metavalue[$i];
$insert_batch []= $insert;
}
$this->db->insert_batch('classifieds_meta', $insert_batch);
1) Create a simple model function just to insert data array. (always try to frame your model functions such that they can be re-used)
function addmeta($data)
(
$this->db->insert('classifieds_meta', $data);
)
2) Now send the required array to the model through the Controller below
array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
)
$listingid=145;
$metakey=array();
$metavalue=array();
if($data['submitlisting'])
{
if($vehicle_make != "")
{
$metakey[]="vehicle_make";
$metavalue[]=$vehicle_make;
}
if($vehicle_mileage != "")
{
$metakey[]="vehicle_mileage";
$metavalue[]=$vehicle_mileage;
}
if($vehicle_year != "")
{
$metakey[]="vehicle_year";
$metavalue[]=$vehicle_year;
}
$insert = array();
for($i=0; $i<count($metakey); $i++)
{
$insert['classifieds_id'] = $listingid;
$insert['meta_key'] = $metakey[$i];
$insert['meta_value'] = $metavalue[$i];
$this->Classifieds_model->addmeta($insert);
}
}
can try this code into controller:
$ex=count($this->input->post('ex'));
$count =count($this->input->post('ex'));
$data2 =array();
for($i=0; $i<$count; $i++)
{
$data2[] = array(
'ex' => $ex[$i],
);
}
$this->db->insert_batch('table', $data2);

PHP: how to return the right stuff

In my function I have more variables:
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
Now, i have a $check parameter. If it contains 'Gallery' the function should return the $disallowGallery variable. If it contains 'Friend' it should return the $disallowFriend variable.
I can do this myself with alot of if else statement / or an switch. But does there exist a more effective/simpler way?
The cleanest way to store this in my eyes would be an array:
$disallow = array(
"Gallery" => 1,
"Friend" => 1,
"Wall" => 1,
"PM" => 1,
"Comment" => 1
);
Inside a check function, you would do a check like so:
function check("Comment")
....
if (array_key_exists($area, $disallow))
return $disallow[$area];
else
return 0;
You can use variable variables:
function isDisallowed($type) {
$disallowGallery = 1;
$disallowFriend = 1;
$disallowWall = 1;
$disallowPM = 1;
$disallowStatusComment = 1;
$type = "disallowed$type";
return isset($$type) ? $$type : 1;
}
But I'd be more tempted to store your configuration in an associative array:
function isDisallowed($type) {
$disallowed = array (
'Gallery' => 1,
'Friend' => 1,
// ...
'StatusComment' => 1,
);
return array_key_exists($type, $disallowed) ? $disallowed[$type] : 1;
}
return ${'disallow' . $check};

Categories