Multiply price and quantity of each row, then sum to calculate total - php

My code goes as:
<?php
$items = array(
array("SKU" => "a49w8dsa", "Title" => "Socks", "Description" => "Sports socks", "Price" => "1.50", "Quantity" => "4"),
array("SKU" => "ta8dla", "Title" => "T-shirt", "Description" => "ABC Brand undershirt", "Price" => "14.25", "Quantity" => "2"),
array("SKU" => "yusa982", "Title" => "Flip Flips", "Description" => "XYZ Brand Beach Flops", "Price" => "2.88", "Quantity" => "5"),
array("SKU" => "gnbaiue", "Title" => "Ball Cap", "Description" => "No Name", "Price" => "3.58", "Quantity" => "1"),
array("SKU" => "ythwq836", "Title" => "Frizbee", "Description" => "Whammo Frisbee Disc", "Price" => "2.47", "Quantity" => "2")
);
$final = array_shift($items);
foreach (array_column as $key => &$value){
$value += array_sum(array_row($Price . $Quantity));
}
unset($value);
var_dump($final);
I want to grab the price of each item, multiply it by the quantity in that array and add the sums to a variable, then print.

Get price of each item into an array, then finally sum it up using array_sum() -
$eachPrice = array();
foreach ($items as $key => $val) {
$eachPrice[] = $val['Price'] * $val['Quantity'];
}
$totalPrice = array_sum($eachPrice);
var_dump($totalPrice); // should be total price of all items

Related

PHP: Keeps return as true

I cant figure out what i´m doing wrong. I keeps returning "På lager" in the if statement. But Shop 3, should return "Ikke på lager" in the foreach loop, where it calls the function.
<?php
$shopsArray = array(
"Shop1" => array (
"price" => 5,
"extUrl" => "https://tv2.dk/",
"logo" => "",
"stock" => "in stock",
"ean" => "5707400342642",
"shopName" => "Shop2",
),
"Shop2" => array (
"price" => 99,
"extUrl" => "https://cnn.com/",
"logo" => "https://eb.dk/",
"stock" => "in stock",
"ean" => "51010101010",
"shopName" => "Shop2.dk",
),
"Shop3" => array (
"price" => 50000000,
"extUrl" => "https://v2.dk/",
"logo" => "https://eb.dk/",
"stock" => "out of stock",
"ean" => "5707406556565655",
"shopName" => "Shop3",
)
);
foreach($shopsArray as $abc){
echo CheckStock();
}
function checkStock(){
global $shopsArray;
foreach ($shopsArray as $stockMgmt) {
if ($stockMgmt["stock"] == "in stock"){
return "På lager";
} else {
return "Ikke på lager";
}
}
}
You return from your checkStock() function as soon as $stockMgmt["stock"] == "in stock", and you do that three times. Try this code instead:
<?php
$shops = [
"Shop1" => [
"price" => 5,
"stock" => "in stock",
"ean" => "5707400342642",
"shopName" => "Shop2",
],
"Shop2" => [
"price" => 99,
"stock" => "in stock",
"ean" => "51010101010",
"shopName" => "Shop2.dk",
],
"Shop3" => [
"price" => 50000000,
"stock" => "out of stock",
"ean" => "5707406556565655",
"shopName" => "Shop3",
]
];
function checkStock($stockManagement)
{
return ($stockManagement["stock"] == "in stock") ? "På lager" : "Ikke på lager";
}
foreach ($shops as $shop => $stockManagement) {
echo $shop . ' = ' . CheckStock($stockManagement) . '<br>';
}
The function now uses the stock management array as an argument. In the function I use the Ternary Operator.
We only use one loop to walk through the main array of shops.
Note how I don't abbreviate unnecessarily. Variable names should clarify the meaning of the value, but not the type. So, not $shopsArray but just $shops or $shopsStock.
Now tested, thanks to medilies: PHP fiddle

How to make a leaderboard

Hey everyone I just made this code in php, where it prints out the list of all students and their score from higher to lower and after that shows the top 3 depending on the score.
<?php
$Turma = array(
array("name" => "Diogo", "score" => "100", "time" => "6" ),
array("name" => "Joao","score" => "500", "time" => "3" ),
array("name" => "Miguel", "score" => "125", "score" => "8" ),
array("name" => "Daniela", "score" => "105", "time" => "7" ),
array("name" => "Joana", "score" => "100", "time" => "6" ),
array("name" => "Diogo", "score" => "275", "time" => "4" ),
array("name" => "Francisco", "score" => "300", "time" => "9" ),
array("name" => "Ines", "score" => "650", "time" => "2" ),
array("name" => "Dionisio", "score" => "101", "score" => "10" ),
array("name" => "Ricardo", "score" => "200", "score" => "8" ),
array("name" => "Fabio", "score" => "201", "score" => "11" ),
array("name" => "Tiago","score" => "50", "score" => "13" ),
array("name" => "Carolina", "score" => "150", "time" => "5" ),
array("name" => "Rui", "score" => "130", "time" => "3" ),
array("name" => "Luisa", "score" => "1000", "time" => "1" ),
);
usort($Turma, function($a,$b){
return $b["score"] - $a["score"];
});
foreach($Turma as $key => $value) {
$position = $key + 1;
echo "{$position}: {$value['nome']} : {$value['score']} <br>";
}
echo "<br>";
echo "WINNERS!! <br> ";
foreach($Turma as $key => $value) {
$position = $key + 1;
if ($position < 4) {
echo "{$position}: {$value['nome']} : {$value['score']} <br>";
}
}
Now i must see if in the main list there are any draws in terms of score and if its true then the fastest wins, if there is a draw in terms of score and time we order by their name
Your code is close; you just need to alter your callback in usort to take into account the time (and name) fields when the score (and time) fields are equal:
usort($Turma, function ($a, $b) {
if ($a['score'] != $b['score']) return $b['score'] - $a['score'];
if ($a['time'] != $b['time']) return $a['time'] - $b['time'];
return strcmp($a['name'], $b['name']);
});
echo "<br>";
echo "WINNERS!! <br> ";
foreach ($Turma as $key => $value) {
if ($key == 3) break;
$position = $key + 1;
echo "{$position}: {$value['name']} : {$value['score']} <br>";
}
Output (for your sample data):
<br>WINNERS!! <br> 1: Luisa : 1000 <br>2: Ines : 650 <br>3: Joao : 500 <br>
Demo on 3v4l.org
Just add a clause to the usort function which compares the time if the difference in score is 0.
function($a, $b){
$diff = doubleval($b["score"]) - doubleval($a["score"]);
if($diff != 0) return $diff;
return doubleval($b["time"]) - doubleval($a["time"]);
}
By the way, some of your array entries seem to have a duplicate score key rather than a score and a time key.
array("name" => "Miguel", "score" => "125", "score" => "8" ),

Table list to be dynamic require with skip approach using multi arrays

I want to be build logic as with below desired result. I have multi arrays which to be listed in table as questionnaire along with skip approach.
Helps are definitely appreciated
Fiddle link also mentioned it :- http://phpfiddle.org/main/code/1sr6-kn5u
<?php
$users = array (
0 => array("user_id" => "217", "user_name" => "S", "id" => "33"),
1 => array("user_id" => "216", "user_name" => "A", "id" => "32"),
2 => array("user_id" => "215", "user_name" => "B", "id" => "31"),
);
$questions = array (
0 => array("text" => "Q1", "type" => "text", "qid" => "1"),
1 => array("text" => "Q2", "type" => "text", "qid" => "2"),
2 => array("text" => "Q3", "type" => "text", "qid" => "3"),
);
$answers = array (
0 => array("SRI" => "31", "qid" => "1", "answer" => "A1"),
1 => array("SRI" => "31", "qid" => "2", "answer" => "A2"),
2 => array("SRI" => "31", "qid" => "3", "answer" => "A3"),
3 => array("SRI" => "32", "qid" => "3", "answer" => "A3"),
4 => array("SRI" => "32", "qid" => "2", "answer" => "A2"),
5 => array("SRI" => "33", "qid" => "1", "answer" => "A1"),
6 => array("SRI" => "33", "qid" => "3", "answer" => "A3")
);
//echo "<pre>";
//print_r($users);
//print_r($questions);
//print_r($answers);
?>
<table border = 1>
<tr>
<th>
User
</th>
<?php
foreach($questions as $key => $Qval){
echo "<th>".$Qval['text']."</th>";
}
?>
</tr>
<?php
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
foreach($answers as $key => $Aval){
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
echo "<th>".$Aval['answer']."</th>";
}
}
}
echo "</tr>";
}
?>
</table>
Desired Result
You need to divise your problem in two steps :
detect if the user answer the current question or not
then display the result
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
$userAnswer = null ; // no user answer per default
foreach($answers as $key => $Aval){ // loop to find a user answer
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
$userAnswer = $Aval['answer']; // save the user answer
break ; // we found the user answer, no need to continue to loop over the remaining answers
}
}
// display the user answer, use a placeholder if none is found
echo '<td>' . (is_null($userAnswer) ? 'SKIP' : $userAnswer) . '</td>' ;
}
echo "</tr>";
}

Php find key for min value in 2D array

I have the following 2D array and I would like to get the key of the smalest value in the [0] column if done is equal to no
$graph= array(
"CityA" => array(
"0" => "1",
"1" => "CityC",
"done" => "no",
),
"CityB" => array(
"0" => "4",
"1" => "CityA",
"done" => "no",
),
"CityC" => array(
"0" => "5",
"1" => "CityA",
"done" => "no",
),
);
Try this,
$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));
Here you go.
$tes = min( array_column( $graph, 0 ) );
$key = array_search( $tes, array_column( $graph, 0 ) );
$array_keys = array_keys($graph);
echo $array_keys[$key];
You should perform all of your checks in a single pass through your array.
My snippet will provide the first qualifying (contains the lowest [0] value AND has a done value of no) row's key.
Code: (Demo)
$graph = [
"CityB" => ["0" => "1", "1" => "CityA", "done" => "no"],
"CityA" => ["0" => "1", "1" => "CityC", "done" => "no"],
"CityD" => ["0" => "1", "1" => "CityD", "done" => "yes"],
"CityC" => ["0" => "5", "1" => "CityA", "done" => "no"]
];
$result = [];
foreach ($graph as $key => $row) {
if ($row['done'] === 'no' && (!isset($result[$key]) || $row[0] < $result[$key])) {
$result[$key] = $row[0];
}
}
echo key($result) ?? 'No "done => no" rows';
Output:
CityB

Get repeated key => values in every array within a multiarray + other no repeated key = > values

i have this multi array "$marray wich has inside some array with some similar key = value and some not look like this :
$marray = array(
array("id" => "1", "be_pro" => 6, "name" => "a1", "service" => 4a),
array("id" => "2", "be_pro" => 6, "name" => "a1", "service" => 4d),
array("id" => "3", "be_pro" => 4, "name" => "a4", "service" => 3d),
array("id" => "4", "be_pro" => 4, "name" => "a4", "service" => 3s),
array("id" => "6", "be_pro" => 4, "name" => "a4", "service" => 34),
array("id" => "8", "be_pro" => 3, "name" => "a3", "service" => 4r),
array("id" => "8", "be_pro" => 3, "name" => "a3", "service" => 4d)
);
So i would like to get new arrays with "id", "be_pro" and "name" once then "service" plus "service" from next array till "be_pro" in the new array is different , so if is different put in the next array.
How should i do this?
what i need is print a multi array and within and array with every row with similar be_pro
This help me:
// first get all bepro_id and put in array
foreach($all_rows as $service){
$bepros[$service['bepro_id']]++;
}
//var_dump($bepros);
//Then for each be pro_id print every row , so print every service , then for be pro_id,id,name just print the first key "[0]" the array inside $new_array
foreach ($bepros as $key=>$bepro){
if(isset($new_bep)){
$x = 0 + $new_bep;
}else{
$x = 0;
}
$new_array[] = array_slice($all_rows,$x,$bepro);
// get where let before
$new_bep=$x + $bepro;
}

Categories