Laravel foreach always returning first data - php

In this foreach, I use a function to pull the scores, I write the value I get from the foreach into the function.
foreach($surveys AS $s) {
$surList[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
}
And in this function returns the message that corresponds to the score we got with case-when in the database
function getSubtitle($id,$score){
$surveys=DB::table("methodolgy")->where("main_survey",$id)->selectRaw("*, (CASE WHEN ".$score." BETWEEN start AND end THEN message ELSE 'bos' END) AS sonuc")->having("sonuc","!=","'bos'")->orderBy("id","ASC")->first();
return isset($surveys->message) ? $surveys->message : "Activity Not Found";
}
The problem is, when I try my query in SQL, the result is correct, but when I try it on my website, it always returns the first record in my methodolgy table.
I couldn't find why it does that.
Thanks for help.

This is because the foreach function always reads the aray and foreach data in the array it does something. For your case it is assigning data to a variable. You can create a variable like $allData and then append every data of the array to it. for example
$surList = [];
foreach($surveys AS $s) {
$oneData[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
$surList.=$oneData;
}

Related

Laravel 8.X validation on attributes that contain a certain string

I'm trying to make an application that saves grocery lists and retrieves them from a database. In the request, the values get passed along in JSON format:
"item:47" => "{"id":47,"name":"Beer","brand":"Jupiler","weight":null,"note":"Six pack;_bottles","order_id":15}"
"item:88" => "{"id":88,"name":"Tomatoes","brand":null,"weight":null,"note":null,"order_id":15}"
"item:110" => "{"id":110,"name":"Gura_Bread","brand":null,"weight":0.3,"note":null,"order_id":15}"
"item:-1" => "{"id":-1,"name":"Beef_Jerky","brand":"Canadon","weight":0.5,"notes":"Spicy_Ones"}"
New items are marked with a descending negative id, while existing items retain their id from the DB
When this arrives in the back-end of the laravel application, I would like to validate the JSON string with Laravel's validate(). The only problem is that the amount of items that can be passed varies in amount. Sometimes it can be one item, while other times it could be 10 items instead.
Is there a way to add this JSON rule that could only trigger when it notices that there's a certain string in one or multiple attributes of an incoming request? In this case, it should trigger when it sees that the string item:.
For context, here are the parameters of an example request.
"picking_method" => "Cheapest"
"item:47" => "{"id":47,"name":"Beer","brand":"Jupiler","weight":null,"note":"Six pack;_bottles","order_id":15}"
"item:88" => "{"id":88,"name":"Tomatoes","brand":null,"weight":null,"note":null,"order_id":15}"
"item:110" => "{"id":110,"name":"Gura_Bread","brand":null,"weight":0.3,"note":null,"order_id":15}"
"item:-1" => "{"id":-1,"name":"Beef_Jerky","brand":"Canadon","weight":0.5,"notes":"Spicy_Ones"}"
"store_street" => "Haag Pines"
"store_number" => "1855"
"store_postal_code" => "82792-01"
"store_city" => "Port Muhammadhaven"
"store_country" => "Guernsey"
"delivery_street" => "Rosenbaum Island"
"delivery_number" => "4974"
"delivery_postal_code" => "61093"
"delivery_city" => "East Carlee"
"delivery_country" => "Slovenia"
"delivery_notes" => null
"medical_notes" => null
After experimenting some more, I came up with this solution.
In order for this method to work, you'll need to have a substring that is the same across all the attributes that you want to check.
Before performing any validation at all, I decided to collect all the attributes that I want to check into an array with a foreach loop. This is where the substring part is important because it will be used to decide which attributes will be collected:
$item_attributes = [];
foreach ($request->post() as $key => $value) {
if (str_contains($key, 'item:')) {
array_push($item_attributes, $key);
}
}
After that, I looped over the $item_attributes array and used it to make a rules array, where every value in the $item_attributes is used as a key. As value, I added the json rule.
$rules = [];
foreach ($item_attributes as $attribute) {
$rules[$attribute] = "json";
}
After that, I validate the data and returned it, so it can be used in the main function of my code:
return $request->validate($rules);
When combined, this will result into the following method:
function validateItems(Request $request)
{
$item_attributes = [];
foreach ($request->post() as $key => $value) {
if (str_contains($key, 'item:')) {
array_push($item_attributes, $key);
}
}
$rules = [];
foreach ($item_attributes as $attribute) {
$rules[$attribute] = "json";
}
return $request->validate($rules);
}

PHP adding to a multidimensional array

I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get
$result['id']
$result['company']
for each row of the returned database suggestiions
This works fine and currently I loop over the results
foreach ($result as $item) {
$suggest[] = $item['company'];
}
echo json_encode($suggest);
I want though to add these so the company is a label and id is a value, something like
"value": "A Company", "data": "20"
This I can then encode and use in my autosuggest.
Thanks in advance!
You have to save an array to main array like this
foreach ($result as $item) {
$suggest[] = [
'value' => $item['company'],
'data' => $item['id'],
]
}
echo json_encode($suggest);
And it should return something like this
[
{
'value': 'Some value',
'data' : item id
}
]
i will recommend you create an array, next create 2 more arrays as values for the value and data keys.
like this.
$arr=array();
$arr['value']=array();
$arr['data']=array();
while($suggest=mysql_fetch_assoc($result)){
array_push($arr['value'],$suggest['id']);
array_push($arr['data'],$suggest['company']);
}
echo "<pre>";
print_r($arr);
note that with this solution, if you delete an entry in either value or data
be ready to delete the corresponding entry in the other array.
others may be able to improve this or even offer a better approach.

get first element of an array

Lets assume, the return value of an search-fuction is something like this
// If only one record is found
$value = [
'records' => [
'record' => ['some', 'Important', 'Information']
]
]
// If multiple records are found
$value = [
'records' => [
'record' => [
0 => ['some', 'important', 'information'],
1 => ['some', 'information', 'I dont care']
]
]
]
what woul'd be the best way to get the important information (in case of multiple records, it is always the first one)?
Should I check something like
if (array_values($value['record']['records'])[0] == 0){//do something};
But I guess, there is a way more elegant solution.
Edit:
And btw, this is not realy a duplicate of the refered question which only covers the multiple records.
If you want the first element of an array, you should use reset. This function sets the pointer to the first element and returns it.
$firstValue = reset($value['record']['records']);
Edit.. after reading your question again, it seems, you dont want the first element.
You rather want this
if (isset($value['record']['records'][0]) && is_array($value['record']['records'][0])) {
// multiple return values
} else {
// single return value
}
Doing this is kind of error proun and i wouldn't suggest that one function returns different kinds of array structures.
check like this..
if(is_array($value['records']['record'][0])) {
// multiple records
} else {
// single record
}

Best PHP Function To Output One Choice Out of Many

I'm importing a product list, and each item has a department number. Each number correlates with a department, i.e.
Handguns
Used Handguns
Used Long Guns
Tasers
Sporting Long Guns
There are 43 departments. Would I just do one long if statement like:
`<?php
if ($var = 1)
echo "Handguns";
else
if ($var = 2)
echo "Used Handguns";
etc.....
?>`
EDIT: I'm able to get an if statement like this to work:
function test($cat) {
if ($cat = 33)
echo "Clothing";
}
but using any array like this:
`$departments = [
33 => Clothing,
];
function getDepartment($id, $departments) {
echo $departments[$id];
}`
I've been unable to get that to work. I'm using wordpress and putting this in functions.php and calling the function from a plugin.
Should I just stick with a big if Statement?
2nd EDIT: Got it to work by including the array inside the function:
function getDepartment($id, $departments) {
$departments = [
"1" => "Handguns",
"2" => "Used Handguns",
"3" => "Used Long Guns",
"4" => "Tasers",
"5" => "Sporting Long Guns",
"6" => "SOTS ",
...
"41" => "Upper Receivers/Conv Kits",
"42" => "SBR Barrels and Uppers ",
"43" => "Upper/Conv Kits High Cap"
];
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Uncategorized';
}
and inside wpallimport, the category call looked liked this: [getDepartment({column_4[1]})]
Create an array of the departments using their ID as their array key. Then you can access them using basic array variable syntax:
$departments = array(
1 => Handguns,
2 => Used Handguns,
3 => Used Long Guns,
4 => Tasers,
5 => Sporting Long Guns
);
$var = 2;
echo $departments[$var]; // prints "Used Handguns"
You can construct this array however you like. It can be hardcoded in a config file or more likely created from a SQL query.
Just make sure that the key exists in your array before you try to access it or else you get an undefined index error message. You probably would be wise to place this in a function so you can abstract this code and reduce duplicated code on each attempt to access this array.
function getDepartment($id, $departments) {
if (isset($departments[$id])) {
return $departments[$id];
}
return 'Invalid Department'; // or whatever you want if the value doesn't exist
}
echo getDepartment(2); // prints "Used Handguns"

Array Mapping function, returns false every time

Ok, trying to make a function that I can pass a variable to, that will search a static currently hardcoded multi dimensional array for its keys, and return the array matched to the key found (if found).
This is what I have thus far.
public function teamTypeMapping($teamType)
{
//we send the keyword football, baseball, other, then we return the array associated with it.
//eg: we send football to this function, it returns an array with nfl, college-football
$mappings = array(
"football" => array('nfl', 'college-football'),
"baseball" => array('mlb', 'college-baseball'),
"basketball" => array('nba', 'college-basketball'),
"hockey" => array('nhl', 'college-hockey'),
);
foreach($mappings as $mapped => $item)
{
if(in_array($teamType, $item)){return $mapped;}
}
return false;
}
And I'd like to make a call to it, example:
teamTypeMapping("football");
Amd have it return the array associated with the key "football", I have tried this a couple ways, and each time I come up false, maybe I am missing something so Im up for taking some advice at this point.
The reason it's not working is that you are looping through the $mappings array, and trying to see if $teamType is in the $item.
There are two problems with your approach:
You are looking in the $item (this is the array('nfl', 'college-football')) for 'football'. This is incorrect.
You are using in_array() which checks if a 'value' is in the array, not the 'key' that you have used. You might want to take a look at the array_key_exists() function - I think this is what you meant to use.
My personal preference is to use isset() instead of array_key_exists(). Slightly different syntax, but both do the same job.
See below for a revised solution:
public function teamTypeMapping($teamType)
{
//we send the keyword football, baseball, other, then we return the array associated with it.
//eg: we send football to this function, it returns an array with nfl, college-football
$mappings = array(
"football" => array('nfl', 'college-football'),
"baseball" => array('mlb', 'college-baseball'),
"basketball" => array('nba', 'college-basketball'),
"hockey" => array('nhl', 'college-hockey'),
);
if (isset($mappings[$teamType]))
{
return $mappings[$teamType];
}
return false;
}
I checked your function
public function teamTypeMapping($teamType)
{
//we send the keyword football, baseball, other, then we return the array associated with it.
//eg: we send football to this function, it returns an array with nfl, college-football
$mappings = array(
"football" => array('nfl', 'college-football'),
"baseball" => array('mlb', 'college-baseball'),
"basketball" => array('nba', 'college-basketball'),
"hockey" => array('nhl', 'college-hockey'),
);
foreach($mappings as $mapped => $item)
{
if(in_array($teamType, $item)){return $mapped;}
}
return false;
}
And when you like to make a call to it, example:
teamTypeMapping("football");
then it return false.
Solution is If your want the array then you want
foreach($mappings as $mapped => $item)
{
if($mapped == $teamType){return $mapped;}
}

Categories