laravel multiple tables exploded data - php

I have this tables where I have inserted multiple imploded data which I can immediately pull from the database as it is just the ID of another table however I cannot show their names on the table
I have an Incident_Table and IncidentType_table I can already show the data but I'm still missing a few things to show the data on my tables instead of just showing 1,3 in my views it should be
1-Police
2-Fire Fighters
3-Ambulance
4-Others
regarding on my code this is what I have so far
public function index()
{
$Incidents = Incident::all(); // I get 1,3 as a collection
// 1 - Police and 3 - Ambulance
foreach ($Incidents as $incident) {
$request_responder = explode(",", $incident->response_needed_id);
for ($i = 0; $i < count($request_responder); $i++) {
$requested_responder[] = ResponderType::with('incident')->get()->where('id', '=', $request_responder[$i]);
}
$requested_responder = implode(',', $request_responder);
}
dd($requested_responder); //show only 1,3 should be Police, Ambulance
return view('dispatch.index', compact('Incidents'));
}

Without seeing your blade template or model, it is difficult to see where the values "1-Police 2-Fire Fighters 3-Ambulance 4-Others" would come from. However, you can solve your current problem from within this current scope by using this.
public function index()
{
$Incidents = Incident::all(); // I get 1,3 as a collection
$incident_type = ['Police', 'Fire Fighters', 'Ambulance', 'Others']; // 1 - Police and 3 - Ambulance
foreach ($Incidents as $incident) {
$request_responder = explode(",", $incident->response_needed_id);
for ($i = 0; $i < count($request_responder); $i++) {
$requested_responder[] = ResponderType::with('incident')->get()->where('id', '=', $request_responder[$i]);
}
$requested_responder = implode(', ', $incident_type[$request_responder-1]); // We minus 1 because the array starts from 0
}
return view('dispatch.index', compact('Incidents', 'requested_responder'));
}

Related

Create a temporary array in PHP to add to a larger array

I am trying to create a number of arrays to add to a larger array which I will then index two dimensionally (for example my_array[i][j]).
I believe I am having some type of pointing issue... I am iterating through a loop.... at the top of each iteration I instantiate a new array with the same name. When I try and view the output each item in the array appears blank.
Is there a better way for me to instantiate the "temp" arrays to fill the larger (outer) array? Really appreciate any and all help, this community has helped me through so many questions :D
$main_array = array();
for($i = 0; $i < $member_count; $i++)
{
$temp_array = array();
//preform SQL query here
$sql_get_member_transactions = 'some SQL query to go to my DB';
foreach($sql_get_member_transactions as $row)
{
//cannot get array to update here
array_push($temp_array, $row['amount']);
}
array_push($main_array, $temp_array);
}
#***FULL CODE BELOW***
$club_transactions = array();
for($i = 0; $i < $member_count; $i++)
{
#create an array for each member in the club,
#add each memeber's array to a larger array once filled with deposit amounts
#here check if member had a deposit (later we will check ALL transaction types...)
#if no deposit on that date add a zero to their array
$temp_member_transactions = array();
$temp_member = my_members[$i];
$sql_member_transactions = "SELECT * FROM Transactions WHERE Date >= '$first_t_date' AND Date <= '$last_t_date' AND RelatedClubID = 'THH'";
$sql_get_member_transactions = mysqli_query($conn, $sql_member_transactions);
//here we will get all transactions that lie within the
//event-transaction-date-window... in otherwords, the date window
//in the year where members transactions occured
foreach($sql_get_member_transactions as $row)
{
//we only want to include the transaction amount
//in the member-specific array if it belongs to that member
//otherwise see "else"
if($row['T_Owner'] == $temp_member)
{
$z = $row['T_Amount'];
}
else
{
//set to 0 so that we still account for the transaction date
$z = 0;
}
array_push($temp_member_transactions, $z);
}
array_push($club_transactions, $temp_member_transactions );

php loop adds extra data to database

I have loop to store my data and it multiple the rows.
example
I have 3 rows with value of test1 and I need to add this rows to become 5
so I have 3 rows already
I add number in input field 2
I loop this 2 number and create new rows
previously 3 rows + 2 new rows = 5 rows in total
but currently I am getting 9 rows.
Code
foreach($request->input('barcodes') as $bb)
{
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bb['serial_number'];
$barcode->save();
}
}
In case you need a full code with logic here I shared it for you.
Any idea why I get more than my desire rows?
Solved
Thanks to u_mulder suggestion here is how I solved my issue
foreach($request->input('barcodes') as $bb)
{
$bbb = $bb['serial_number']; // added to get single serial number
}
for ($i = 0; $i < $request->input('nonuiqueAmount'); ++$i) {
$barcode = new Barcode;
$barcode->product_id = $product->id;
$barcode->returned = false;
$barcode->serial_number = $bbb; // changed
if($barcode->save()) {
$user = Auth::user();
$outlets = $user->outlets;
foreach($outlets as $outlet) {
DB::table('outlet_products')->insert([
'outlet_id' => $outlet->id,
'barcode_id' => $barcode->id,
'created_at' => now(),
'updated_at' => now(),
]);
}
}
}

Code igniter database calculate column average

I need to calculate in a function the average score of a column named: "totalscore" from my database table "score"
I tried to do Active record select_avg() but I am not getting anything.
Any idea how I can do this?
function calculateaverage(){
$dataArr = array();
$data = $this->db->get('score');
$maxrows = $data->num_rows();
$data = $this->db->get('score');
for ($i = 1; $i<= $maxrows-1; $i++){
$this->db->select('totalscore');
foreach ($data->result() as $row) {
$dataArr[$i] = $row->totalscore;
}
}
return $dataArr;
}
You can try this code, very simple and straight forward. write it in your model. use in Controller like $this->yourmodel->calculateaverage;
basically we are telling codeigniter query builder to select the AVG of our totalscore..
function calculateaverage(){
$query = $this->db->select('AVG(totalscore) as average_score')->from('score')->get();
return $query->row()->average_score;
}

Get all possible combinations of a PHP Array split in two

Im working on a code for generating a sports teams. I have an array with a list of players and want to store on another array all the possible team cobinations.
To make it simple, lets imagine a tennis match, where you have 4 players that will be split into two teams.
$players = array("Federer","Del Potro","Nadal","Murray");
The output array should look something like this:
$combinations[0][0] = "Federer","Del Potro";
$combinations[0][1] = "Nadal","Murray";
$combinations[1][0] = "Federer","Nadal";
$combinations[1][1] = "Del Potro","Murray";
$combinations[2][0] = "Del Potro","Nadal";
$combinations[2][1] = "Federer","Murray"; .. and so forth..
Any help?
Thanks in advance!
/// -- Edit
This is the code I have so far. All players also have a score and I store this score for later usage. Its not really important. I think I've got it working but im not sure this code gets ALL the possible combinations. What I do is I loop "player count" times and start building teams, after a team is built , I move the second player of the list to the bottom of the array and loop again.
//-- Get the Max Players and the Array of Player Names
$max_players = count($players)/2;
$p = array_keys($players);
for($i=0;$i<=(count($p));$i++){
$tmp = array();
$t=0;
//-- Loop and start placing players into a team. When the max is reached, start placing on the other team.
foreach($p as $player) {
//-- Store player on Team
$tmp[$t][] = $player;
if(count($tmp[$t])==$max_players) {
$t++;
}
}
//-- Get the second player and move it to the bottom of the list.
$second = $p[1];
unset($p[1]);
$p[] = $second;
$p = array_values($p);
//-- Loop thru teams and add the score of each player
foreach($tmp as $key=>$eq) {
$score = 0 ;
foreach($eq as $jug) {
//-- Add Score for each player
$score += floatval($players[$jug]["score"]);
}
//-- Store the sum of scores of all players in team
$tmp[$key]["score"] = $score;
}
//-- Store the Difference between team scores in this "team set"
$tmp["diff"] = abs(round($tmp[0]["score"]-$tmp[1]["score"],2));
$teams[] = $tmp;
}
Just googled and found these results from stackoverflow.com
Get all combinations of a PHP array
algorithm that will take numbers or words and find all possible combinations
PHP: How to get all possible combinations of 1D array?
$player_combination = [];
$match_combination = [];
$players = array("Federer","Del Potro","Nadal","Murray");
for($i = 0; $i< count($players);$i++){
for($j=$i+1;$j<count($players);$j++){
$player_combination[] = [$players[$i],$players[$j]];
}
}
for($i = 0; $i< count($player_combination);$i++){
for($j=$i+1;$j<count($player_combination);$j++){
if(($player_combination[$i][0] !== $player_combination[$j][0]) && ($player_combination[$i][0] !== $player_combination[$j][1])&& ($player_combination[$i][1] !== $player_combination[$j][0]) && ($player_combination[$i][1] !== $player_combination[$j][1]))
$match_combination[] = [$player_combination[$i],$player_combination[$j]];
}
}
my webiste is 9amobile.com

Multidimensional Arrays in PHP

How do i add items into a multidimensional array? Basically i am making an application which calculates what people are buying in a suppermarket and how much of it.
Sue buys 2 tubs of butter and 1.
toothpaste
John buys 1 peach and 1 banana.
I think the array would look something like this
$sue[butter] = array();
$sue[butter][] = 2;
$sue[toothpaste] = array();
$sue[toothpaste][] = 1;
$john[peach] = array();
$john[peach][] = 1;
$john[banana] = array();
$john[banana][] = 1;
My current code can only record the item and the item quantity.
public $items = array();
public function AddItem($product_id)
{
if (array_key_exists($product_id , $this->items))
{
$this->items[$product_id] = $this ->items[$product_id] + 1;
} else {
$this->items[$product_id] = 1;
}
}
I just dont know how to put this inside an array for each person.
Thanks!
Instead of doing this, you might find it easier to encapsulate into a class. For instance, have each person be a class, and then give them attributes.
Once you get into multidimensional arrays, it becomes more difficult to maintain your code.
For instance (this is pseudocode):
class Customer {
//this is an array of FoodItem objects.
private $foodItems[];
// any other methods needed for access here
}
class FoodItem {
//could be a String, or whatever it needs to be
private $itemType;
//the number of that item purchased
private $numPurchased;
}
Hm, maybe I fail to see the multi-dimensionality here?
$sue = array();
$sue['butter'] = 2;
$sue['toothpaste'] = 1;
$john = array();
$john['peach'] = 1;
$john['banana'] = 1;
I think the function you've shown would work with the above.
You dont need to create another array to hold the number of items like you did here:
$sue[butter] = array();
$sue[butter][] = 2;
I think something like this would work:
$customers[sue][butter] = 2;
$customers[sue][toothpaste] = 1;
$customers[john][peach] = 1;
$customers[john][banana] = 1;
This way you create an array of customer names. Then in each customer array you have an array of their products. Then each product holds the number of that product the customer bought.
$data = array();
$data["persons"] = array("Sue","John");
$data["articles"] = array("butter","toothpaste","peach","banana");
$data["carts"] = array();
$data["carts"][0][0] = 2; // sue's 2 butter packets
$data["carts"][0][1] = 1; // sue's 1 tooth paste
$data["carts"][1][2] = 1; // john's peach
$data["carts"][1][3] = 1; // john's banana

Categories