Best PHP Function To Output One Choice Out of Many - php

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"

Related

Laravel foreach always returning first data

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;
}

Eloquent first() and loops

I'm new to Eloquent and I'm having trouble when using it with loops.
Imagine I have a table in my db called ‘Jobs’ with:
Id – 1; value: engineer
Id – 2 ; value: doctor
Id – 3 ; value: nurse
I'd also have a JobTranslations table with each job translations. Then, I have this piece of code:
$jobTranslations = [];
$lang = $request->input('lang') ?? 'pt';
foreach(Job::all() as $job) {
$job = $job->with(['jobtranslations' => function($query) use ($lang) {
$query->where('languageCode', $lang);
}])->firstOrFail();
$jobTranslations[] = $job;
}
return ['translatedJobs' => $jobTranslations];
When I run this code, I’m expecting to get an array (jobTranslations) with those 3 jobs in it and each job’s translation.
However, I get instead an array with three items, but they’re all the same:
array([‘id’ => 1, ‘value’ => ‘engineer’, ‘jobtranslations’ => [another array]],
[‘id’ => 1, ‘value’ => ‘engineer’, ‘jobtranslations’ => [another array]],
[‘id’ => 1, ‘value’ => ‘engineer’, ‘jobtranslations’ => [another array]]
);
I’ve realized this is happening due to ‘firstOrFail’ but I don’t understand why. $job->firstOrFail() doesn’t make sense to me because it’s only one job (the current one in the loop) but I don’t want to use get() either.
In C#, using EF, I’d do something like this (no need to call get or first):
foreach(var job in jobs) {
translatedJobs.Add(job.Include(j => j.jobtranslations.FirstOrDefault(jt => jt.languageCode == lang)));
}
return translatedJobs;
Thanks in advance!
I assum what you ar looking for ist this:
$lang = $request->input('lang', 'pt');
$jobTranslations = Job::with([
'jobtranslations' => function ($query) use($lang)
{
$query->where('languageCode', $lang);
}
])->get()->toArray();
return ['translatedJobs' => $jobTranslations];
There is no need to do a Foreach Loop if you setup your Model correct.

Does PHP allow to have duplicate properties inside an stdObject?

I'm stuck with a very weird bug. I have an object called $row that looks like this:
stdClass Object
(
[title] => Some Title
[body] => My body
[topic] => Topic
[dataType] => Survey
[csvrownum] => 1
)
I'm just trying to print out the title property in the following way:
print_r($row->title);
However for some reason that doesn't output anything.
Then I've tried to manually set the title property and print it right after, something like this:
$row->title = 'My Title';
print_r($row->title);
Surprisingly it worked but why? To make this more strange I decided to var_dump the object after set the title variable by hand:
$row->title = 'My Title';
var_dump($row);
And this is what I've got:
class stdClass#391 (6) {
public $title =>
string(3) "Some title"
public $body =>
string(7) "My body"
public $topic =>
string(6) "Topic"
public $dataType =>
string(17) "Survey"
public $csvrownum =>
int(1)
public $title =>
string(8) "My title"
}
Notice the title key is duplicated with different values. Is there any condition under this could happen?
No, PHP does not allow an object to have duplicate property names, because objects in PHP are implemented just like arrays. They are both implemented as ordered hashmaps. In a hashmap, two things that have the same hash, overwrite each other.
You likely just have unprintible characters in your object property name. You can see this more clearly by doing something like the following for debug purposes...
foreach($row as $key => $value) {
var_dump($key);
}
If we had an object like this, for example, you'd see it gets overwritten.
$row = new stdClass;
$row->title = "First";
$row->title = "Second";
But something like this might be more deceptive...
$row = new stdClass;
$row->{"title\0"} = "First";
$row->title = "Second";
Output from the foreach using var_dump on the key, would reveal this...
string(6) "title"
string(5) "title"
Notice one is string of length 6 and the other is a string of length 5.
Grain of salt
It's always better to use var_dump when attempting to debug variables than using something like print_r, as var_dump was specifically designed for debug purposes, whereas print_r is just a recursive print (hence the name). Printing values like null, false, or empty strings, gives you no useful information for debug purposes, but var_dump does.

Multiple Keys to an array in if/else search

My code is pretty basic. I'm using an array to generate a datasheet for a product based on it's SKU and a filepath.
My array looks like this:
$a=array(
"/images/ManualSheets/factSheetCLASSIC.pdf"=>"KE800/6",
"/images/ManualSheets/factSheetMICRO.pdf"=>"KE800/12",
"/images/ManualSheets/factSheetSMALL.pdf"=>"KE4000/12",
"/images/ManualSheets/factSheetMEDIUM.pdf"=>"KE8000/12",
);
Where the first Key is the filepath, and the second Key is the SKU (as generated by the system) I then use an if/else to generate a button - so if a product is not in the array it returns a blank value and doesn't have a button which leads to nowhere
$factsheetweblink_url = array_search($product_sku,$a);
if ($factsheetweblink_url==false) {
echo " ";
}
else {
echo "<div class='productpagestockistBTN'>
<img src='/images/FactSheet_btn.png' >
</div>";
}
?>
This code works fine. The catch comes when I have products with different SKUs but the same datasheet file, (same brand and make but a different model). Currently I can only get it to work by uploading multiple copies of the datasheets with different names, but it's becoming a big waste of space.
I have tried using an array as a key to hold multiple values to the one key..
"/images/ManualSheets/factSheetMEDIUM.pdf"=> array("KE8000/12","KE7000/12"),
but it doesn't seem to be working... I'm not quite sure if I need to refine my if statement to search within the sub arrays as well or..?
Any help would be appreciated, thanks in advance.
You should use arrays like this:
$products = array(
0 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC.pdf",
"skus" => array("KE800/6","KE900/6")
),
1 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC3.pdf",
"skus" => array("KE100/6","KE200/6"))
);
This is because array_search returns just first row whit that key.
Then just do your own search function like:
function findBySku($items, $sku) {
$pdf = ""; // return empty if not found.
foreach($items as $row) {
if (in_array($sku, $row['skus'])) {
$pdf = $row['pdf'];
break;
}
}
return $pdf;
}
and call that function:
$pdf = findBySku($products, "some sku");

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