Getting Undefined offset: 2 error on foreach loop - php

Here is the code :
foreach ($test_scores as $score) {
switch ($score['name']) {
case 'LE-TOD':
$le_tod = $score['banding'];
$le_tod_desc = $score["result_desc"];
if($score['std_score'] == 0) {
$le_tod_small = $scoring['tod']['no_pref_bottom'];
}
else {
$le_tod_small = $scoring['tod']['pref_bottom'].$score['banding'];
}
break;
This is where I get the error message :
public static function generateLSPReportFile($dataInput, $auto_download = true)
{
$file_type = $dataInput['file_type'];
$test_type_id = $dataInput['test_type_id'];
$he_she = array('male' => 'He', 'female' => 'She');
$his_her = array('male' => 'his', 'female' => 'her');
$candidate = \Candidate::where('id',$dataInput['candidate_id'])->first();
if(!$candidate)
return;
$candidate = $candidate->toArray();
$candidate_name = $candidate['first_name'].' '.$candidate['last_name'];
$order = \Order::with('client')->find($dataInput['order_id']);
if(!$order)
return;
$client = $order->client;
$order = $order->toArray();
//for test dates
$order_candidate = \OrderCandidate::candidateId($dataInput['candidate_id'])->orderId($dataInput['order_id'])->first()->toArray();
$order_tests = \OrderCandidateTest::orderCandidateId($order_candidate['id'])
->status(\Config::get('kcg.candidate_test_status_taken'))
->testId($dataInput['test_id'])
->with(array('test' => function($query){
$query->select(['id', 'name', 'description', 'abbreviation']);
}));
$tests_scores = \OrderCandidateTestScore::orderId($dataInput['order_id'])
->candidateId($dataInput['candidate_id'])
->testId($dataInput['test_id'])
->with(array('test' => function($query){
$query->select(['id', 'name', 'description', 'test_type_id']);
}));
$test_type = TestType::find($test_type_id);
$test_scores = $tests_scores->orderBy('sequence_no')->get()->toArray();
$order_tests = $order_tests->get()->toArray();
if(!$order_tests)
return;
if(!$tests_scores)
return;
It posted an error : ErrorException Undefined offset: 2. I'm really not sure what's causing this.
What am I doing wrong here? Please help me. Thank you

Typically, the Undefined offset message would be triggered by trying to access an array key which doesn't exist.
It seems that your code example might not actually be showing the part that triggered the error... In your case, I would expect the code to show something like $var[2], where the array does not actually contain an index of 2.
See this other question for a clearer representation of what that error means.

Related

im trying to make a query on laravel but it's returning this error message

I'm trying to get all item series from a deposit but the deposit id is on a related table. On this function i'll list all the series between two sequences requested
public function getSeries($params = [])
{
$data = collect($params);
$inicio = $data->only('serie_in');
$fim = $data->only('serie_fi');
$depOrigem = $data->only('id_origem');
$series = [];
for($i = $inicio; $i <= $fim; ++$i)
{
$item = Item::leftJoin('produtoItem', 'produtoItem.id', '=', 'item.id_produtoItem')->where('serie', $i)->where('produtoItem.id_deposito', $depOrigem)->first();
if(empty($item))
{
$status = 'I';
}
else
{
$status = $item->status;
}
$series[] = [
'serie' => $i,
'status' => $status
];
}
$result = [
'status' => true,
'data' => $series
];
return $result;
}
This is the error message, i'm thinking that must be as sintax error, but a dont realy know what? Can you help me?
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 2031 (SQL: select * from item left join produtoItem on produtoItem.id = item.id_produtoItem where serie = ? limit 1) in file /usr/share/nginx/html/controleestoque/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671
I was calling the request on my controller without a validator, so i rewrite the getSeries method.
public function getSeries(Request $request){
$data = $request->only(['serie_in', 'serie_fi', 'id_origem']);
$result = $this->produto_service->getSeries($data);
return response()->json($result);
}
And my function work it !

Creating default object from empty value for information

I'm trying to edit and save some articles, but I receive this error : Creating default object from empty value. What's wrong in my code?Because, at edit I have my subject, but and submit I get this error.
My error : https://imgur.com/a/eWGqc5B
Controller
public function update($type, $id)
{
/* print_r(Input::all()); die; */
if($type == "News")
{
$article = \App\News::find($id);
$article->subject = Request::input('subject');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->information = Request::input('information');
$article->update();
}
if($type == "Event")
{
$article = \App\Event::find($id);
$article->subject = Request::input('subject');
$comm->comments = Request::input('comments');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->event_type_id = Request::input('event_type_id');
$article->country = Request::input('country');
$article->starts = Request::input('starts');
$article->ends = Request::input('ends');
$article->organizer = Request::input('organizer');
$article->address = Request::input('address');
$article->city = Request::input('city');
$article->website = Request::input('website');
$article->email = Request::input('email');
$article->telephone = Request::input('telephone');
$article->information = Request::input('information');
$article->update();
}
return redirect(URL::previous());
Line 669 in ArticleController.php
$article->subject = Request::input('subject');
Here is my editEvent code : https://codepen.io/anon/pen/YodwKO
my articles.blade code : https://codepen.io/anon/pen/jjXWOb
My route:
`
Route::post('admin/article/update/{type?}/{id?}', [ 'as' => 'update.article', 'uses' => 'ArticleController#update']);
`
The variable $comm is not defined. It looks like a typo.

Why is there not enough memory in the simplest loop and with an array of 3 elements?

There is a function that displays categories ranging from the very top:
function getFullCategoryName($strCategoryId, $arrCategories)
{
$strCategoryIdPaent = NULL;
$arrCategoryCurr = isset($arrCategories[$strCategoryId]) ? $arrCategories[$strCategoryId] : NULL;
$arrCategoriesNames = [];
while (is_array($arrCategoryCurr)) {
$arrCategoriesNames[] = $arrCategoryCurr['title'];
if ($arrCategoryCurr['parentId'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
$arrCategoryCurr = $arrCategories[$arrCategoryCurr['parentId']];
} else {
$arrCategoryCurr = NULL;
}
}
krsort($arrCategoriesNames);
return implode(' > ', $arrCategoriesNames);
}
With just 3 array elements, I get an error:
"Allowed memory size of 134217728 bytes exhausted"
I understand that I am using something wrong. Please, help me understand what exactly.
This is my input array:
$arrCategories = array (
193450 =>
array (
'id' => '193450',
'parentId' => '193450',
'title' => 'Blood glucose meter',
),
193451 =>
array (
'id' => '193451',
'parentId' => '193450',
'title' => 'Sugar test strips',
),
193452 =>
array (
'id' => '193452',
'parentId' => '193452',
'title' => 'Blood glucose meter',
),
);
This is the call to the function:
$strCategoryId = 193450;
getFullCategoryName($strCategoryId, $arrCategories);
The while (is_array($arrCategoryCurr)) loop never ends as the else block of $arrCategoryCurr = NULL; is never called.
This happens because you have a loop where a node id is the same as his parent id. Look at your array:
....
'id' => '193450',
'parentId' => '193450',
...
To fix it modify the if statement to:
if ($arrCategoryCurr['parentId'] && $arrCategoryCurr['parentId'] != $arrCategoryCurr['id'] && isset($arrCategories[$arrCategoryCurr['parentId']])) {
Your (sample) data has an issue based on my reading of your function.
The parentId and index are the same in some items. This would create an infinite loop based on what I can work out from the question.
A better structure would be something like the following, with some error checking in the loop:
function getFullCategoryName($strCategoryId, $arrCategories) {
// set a base / default value
$arrCategoriesNames = [];
// do we even have anything to work with?
if (isset($arrCategories[$strCategoryId])) {
// at least one entry
do {
// get the title
$arrCategoriesNames[] = $arrCategories[$strCategoryId]['title'];
// get the next id and error check the data
if ((isset($arrCategories[$strCategoryId]['parentId'])) &&
($strCategoryId != $arrCategories[$strCategoryId]['parentId'])) {
// next index found and not the same
$strCategoryId = $arrCategories[$strCategoryId]['parentId'];
} else {
// either no parentId or a parentId that matches the current
// index. If that is the case, go no further.
$strCategoryId = false;
}
// you could add another error check if you like.
// if (count($arrCategoriesNames) == count($arrCategories)) {
// // go no further as data has a loop
// $strCategoryId = false;
// }
} while($strCategoryId);
// sort the data? why?
krsort($arrCategoriesNames);
}
// return a string
return implode(' > ', $arrCategoriesNames);
}
And testing you sample array;
$result = getFullCategoryName(193450,$arrCategories);
var_dump($result);
Returns the following:
string(19) "Blood glucose meter"

Laravel Error: Only variable references should be returned by reference

I am working on a web app with php laravel framework. I'm also using framwork eloquent.
When i create a new "user" and i send it to my database the error with
$myValue->save();
This is the error:
"at HandleExceptions->handleError(8, 'Only variable references should be returned by reference',
'C:\\wamp64\\www\\project\\Fiq-spsslsj\\app\\Http\\Controllers\\DossierController.php', 97, array('request' => object(Request), 'employe' => object(employe)))
in DossierController.php line 97"
I've seen some similar problem but they are not quite really usefull (the problem in the other topics talk about code ingniter and common.php).
public function ajouter(Request $request){
$employe = new employe;
$employe->No_Employe = $request->input('No_Employe');
$employe->Nom = $request->input('Nom');
$employe->Prenom = $request->input('Prenom');
$employe->Email = $request->input('Email');
$employe->Adresse = $request->input('Adresse');
$employe->Date_Naissance = $request->input('Date_Naissance');
$employe->Titre_Emploi = $request->input('Titre_Emploi');
$employe->Telephone = $request->input('Telephone');
$employe->Annee_Embauche = $request->input('Annee_Embauche');
$employe->Present_Travail = $request->input('optTrav');
$employe->Sexe = $request->input('optSexe');
$employe->Fumeur = $request->input('optFum');
$employe->Langue = $request->input('Langue');
if (DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->get() != null)
{
$employe->Fk_Id_Ville = DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->value('Id_Ville');
}
else
{
$newVille = ucfirst($request->input('Ville'));
DB::table('liste_ville')->insertGetId(['Nom_Ville' => $newVille]);
$MoreVille = DB::table('liste_ville')->get();
foreach ($MoreVille as $key => $v)
{
if(strtolower($request->input('Ville')) === strtolower($v->Nom_Ville)){
$employe->Fk_Id_Ville = $v->Id_Ville;
break;
}
}
}
$employe->Code_Postal = $request->input('Code_Postal');
$employe->Actif = $request->input('optActif');
if (DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->get() != null) {
$employe->Fk_Id_Province =DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->value('Id_Province');
}
else
{
$newProv = ucfirst($request->input('Province'));
DB::table('provinces')->insertGetId(['Nom_Province' => $newProv]);
foreach ($provinces as $key => $p)
{
if(strtolower($request->input('Province')) === strtolower($p->Nom_Province)){
$employe->Fk_Id_Province = $p->Id_Province;
break;
}
}
}
$employe->save();
return redirect('/dossiers');
}
The code above is the code in my controller.
I hope you'll be able to help me.
Try this in your controller
return redirect()->to('/dossiers');

Undefined variable Array Slim Application

I am getting this error that runs fine on one of my servers with php 5.4 I transfered the code to a new server with php 5.5.9 and now I am getting this error:
Details
Type: ErrorException
Code: 8
Message: Undefined variable: propertylist
File: /var/www/subdomains/api/index.php
Line: 57
Trace
The code:
$app->get("/propertylist/", function () use ($app, $db) {
$app->response()->header("Content-Type", "application/json");
ob_start('ob_gzhandler');
$req = $app->request();
$bed = $req->get('bed');
$bath = $req->get('bath');
$city = $req->get('city');
$zip = $req->get('zip');
if($bed ==''){$bed=0;}
if($bath ==''){$bath=0;}
if($zip ==''){
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("City LIKE ?", "%$city%")->where("BathsTotal >= ?", $bath);
}else{
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("ZipCode LIKE ?", "%$zip%")->where("BathsTotal >= ?", $bath);
}
foreach ($properties as $property) {
$propertylist[] = array(
"MLSnumber" => $property["MLnumber"],
"ListPrice" => number_format($property["ListPrice"]),
"StreetNumber" => $property["StreetNumber"],
"StreetName" => $property["StreetName"],
"SqFt" => $property["SquareFootageStructure"],
"PropertyDescription" => summaryMode($property["PropertyDescription"],15),
"Bedrooms" => $property["Bedrooms"],
"BathsTotal" => $property["BathsTotal"],
"LO_Name" => $property["LO_Name"]
);
}
echo json_encode($propertylist);
});
You need create/define variable before use:
$app->get("/propertylist/", function () use ($app, $db) {
$app->response()->header("Content-Type", "application/json");
ob_start('ob_gzhandler');
$req = $app->request();
$bed = $req->get('bed');
$bath = $req->get('bath');
$city = $req->get('city');
$zip = $req->get('zip');
if($bed ==''){$bed=0;}
if($bath ==''){$bath=0;}
if($zip ==''){
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("City LIKE ?", "%$city%")->where("BathsTotal >= ?", $bath);
}else{
$properties = $db->rets_property_listing_mrmls_resi->limit(2500,0)->where("Bedrooms >= ?", $bed)->where("ZipCode LIKE ?", "%$zip%")->where("BathsTotal >= ?", $bath);
}
$propertylist = array(); //Create variable type array
foreach ($properties as $property) {
$propertylist[] = array(
"MLSnumber" => $property["MLnumber"],
"ListPrice" => number_format($property["ListPrice"]),
"StreetNumber" => $property["StreetNumber"],
"StreetName" => $property["StreetName"],
"SqFt" => $property["SquareFootageStructure"],
"PropertyDescription" => summaryMode($property["PropertyDescription"],15),
"Bedrooms" => $property["Bedrooms"],
"BathsTotal" => $property["BathsTotal"],
"LO_Name" => $property["LO_Name"]
);
}
echo json_encode($propertylist);
});
I think that version of PHP just changed the variables' scope, now it's more like you expect in other languages. If you define/create a variable in a block, it's not visible in the outer scope.
In your case, $propertylist is defined directly in the foreach block scope, hence it isn't visible to the rest of the code, causing the error.
As #Guilherme Nascimento suggested, you have to define it outside the loop.
That's said, in PHP is perfectly fine (but not recommended) to use a variable without instantiate it:
$var[] = 1;
// => array(1)

Categories