I have this kind of array :
$arrVar = array(
0 => array(
'val'=> 9
),
1 => array(
'val'=> 12,
),
2 => array(
'val'=> 4
),
);
How do I make a function that returns the index of an array based on a variable $myVar?
For example :
if $myVar = 4 the function will return $arrVar['2']
if $myVar = 8 the function will return $arrVar['2']
if $myVar = 10 the function will return $arrVar['0']
This is my array
$arrVar = array(
0 => array(
'qty'=>9,
'disc'=> 0.15
),
1 => array(
'qty'=>12,
'disc'=> 0.20
),
2 => array(
'qty'=>4,
'disc'=> 0.10
),
);
when customer A buy 4 products he will get disc 10%
or when customer A buy 8 products he will get disc 10%
or when customer A buy 10 products he will get disc 15%
Use following php function to calculate your discount percentage:
function searchArr($needle) {
global $arrVar;
$arr=array();
foreach($arrVar as $key => $value) {
$vals = array_values($value);
$arr[$vals[0]] = $vals[1];
}
ksort($arr);
$prev=0;
foreach($arr as $key => $value) {
if ($needle < $key)
return 100 * ($prev==0 ? $value : $prev);
$prev = $value;
}
return 100 * $prev;
}
TESTING:
echo "Discount: " . searchArr(4) . "%\n";
echo "Discount: " . searchArr(8) . "%\n";
echo "Discount: " . searchArr(10) . "%\n";
echo "Discount: " . searchArr(12) . "%\n";
OUTPUT:
Discount: 10%
Discount: 10%
Discount: 15%
Discount: 20%
See this code running here: http://ideone.com/zLDen
Related
This question already has an answer here:
get cheap price with min() from array
(1 answer)
Closed 7 months ago.
I have an array like this:
$flight = array (
array (
"home" => "AMS",
"away" => "LHR",
"price" => "270"
),
array (
"home" => "AMS",
"away" => "LGW",
"price" => "216"
),
array (
"home" => "EIN",
"away" => "LHR",
"price" => "427"
)
);
I want the values from the cheapest flight. The result should be: AMS LGW 216.
When I loop trough the array I can get the lowest price result but not the other values from the array home and away.
foreach ($flight as $value) {
echo $value["home"].' '.$value["away"].' '.$value["price"].'<br>';
$lowest = array_column($flight, "price");
$min = min($lowest);
}
echo $min;
The result now is only 216
But the result I want AMS LGW 216
How can I create this?
One option is to remember what the values were at the lowest price and just iterate over all of them:
$min = null;
foreach ($flight as $value) {
if ($min === null || $value['price'] < $min) {
$minValue = $value;
$min = $value['price'];
}
}
echo $minValue["home"].' '.$minValue["away"].' '.$minValue["price"];
Store the entire item not just the price.
$min = ["price" => 1e10];
foreach ($flight as $value) {
echo $value["home"] . ' ' . $value["away"] . ' ' . $value["price"] . '<br>';
if ($value['price'] < $min['price']) {
$min = $value;
}
}
print_r($min);
Sort the array by field (ASC order) and you'll find the lowest element in the head of your array:
usort($flights, fn($a, $b) => $a['price'] <=> $b['price'])
print_r($flights[0]);
You can use array_keys and with your code.
Here is the code:
$flight = array(
array(
"home" => "AMS",
"away" => "LHR",
"price" => "270"
),
array(
"home" => "AMS",
"away" => "LGW",
"price" => "216"
),
array(
"home" => "EIN",
"away" => "LHR",
"price" => "427"
)
);
$lowest = array_column($flight, "price");
$lowset_array = array_keys($lowest, min($lowest));
print_r($flight[reset($lowset_array)]);
//OR
//print_r($flight[$lowset_array[0]]);
And here is the output:
Array
(
[home] => AMS
[away] => LGW
[price] => 216
)
Before providing solutions: your implementation it's finding the lowest price several times (the number of flights). You can get the cheapest price with:
$lowest = array_column($flight, 'price');
echo min($lowest);
You may use two variables to save the lowest price and the associated flight:
function getCheapestFlight(array $flights): array
{
$cheapestFlight = null;
$lowest = PHP_INT_MAX;
foreach ($flights as $flight) {
$price = $flight['price'];
if ($price < $lowest) {
$lowest = $price;
$cheapestFlight = $flight;
}
}
return $cheapestFlight;
}
Or use only one variable for the cheapest flight:
function getCheapestFlight(array $flights): array
{
$cheapestFlight = reset($flights);
foreach ($flights as $flight) {
$price = $flight['price'];
if ($price < $cheapestFlight['price']) {
$cheapestFlight = $flight;
}
}
return $cheapestFlight;
}
If you prefer functional programming:
function getCheapestFlight(array $flights): array
{
return array_reduce(
$flights,
function ($cheapestFlight, $flight) {
return $flight['price'] < $cheapestFlight['price']
? $flight
: $cheapestFlight;
},
reset($flights)
);
}
I have a question about how to make an iteration. I want to place a total row after each item in the array if the next element in the array matches a specific condition. Spesific conditions have logic like this
the data like this
if i request a qty for example = 60 the result i hope like this
you can see
data[2] = 01/03/2020 just took 10 out of 40
$iter = new \ArrayIterator($values);
$sum = 0;
foreach($values as $key => $value) {
$nextValue = $iter->current();
$iter->next();
$nextKey = $iter->key();
if(condition) {
$sum += $value;
}
}
dd($iter);
how to make this logic work on php language/ laravel?
Following logic might help you on your way:
<?php
$stock = [
'01/01/2020' => 20,
'01/02/2020' => 30,
'01/03/2020' => 40
];
showStatus($stock, 'in stock - before transaction');
$demand = 60;
foreach ($stock as $key => $value) {
if ($value <= $demand) {
$stock[$key] = 0;
$supplied[$key] = $value;
$demand -= $value;
} else {
$stock[$key] -= $demand;
$supplied[$key] = $value - ($value - $demand);
$demand = 0;
}
}
showStatus($supplied, 'supplied');
showStatus($stock, 'in stock - after transaction');
function showStatus($arr = [], $msg = '')
{
echo $msg;
echo '<pre>';
print_r($arr);
echo '</pre>';
}
?>
**Output:**
in stock - before transaction
Array
(
[01/01/2020] => 20
[01/02/2020] => 30
[01/03/2020] => 40
)
supplied
Array
(
[01/01/2020] => 20
[01/02/2020] => 30
[01/03/2020] => 10
)
in stock - after transaction
Array
(
[01/01/2020] => 0
[01/02/2020] => 0
[01/03/2020] => 30
)
Working demo
I'm not sure I've understood you correctly but this might help:
$values = [
'01/01/2020' => 20,
'01/02/2020' => 30,
'01/03/2020' => 40
];
$demand = 60;
$total = array_sum($values);
$decrease = $total - $demand; //(20+30+40) - 60 = 30
$last_key = array_keys($values,end($values))[0]; //Is 01/03/2020 in this case
$values[$last_key] -= $decrease; //Decrease value with 30 calulated above
Would output:
Array
(
[01/01/2020] => 20
[01/02/2020] => 30
[01/03/2020] => 10
)
I got the first(main) array as below,
$groceritems = array(
"apple" => array(
"price"=>"10",
"origin"=>array("australia","belgium","USA","canada"),
"breed"=>array("gala","fuji","Honeycrisp","washington"),),
"orange" => array(
"price"=>"10",
"origin"=>array("australia","belgium","USA","canada"),
"breed"=>array("gala","fuji","Honeycrisp","washington"),
),
);
foreach ($groceritems as $key => $value) {
$origins = $value['origin'];
$breeds= $value['breed'];
foreach (array_combine($origins, $breeds) as $origin=>$breed) {
echo $breed ." ".$key." from ". $origin ." price is RM ". $value['price'];
echo "<br>";
}
}
second array as below,
$grocer= array(
"apple" => array( "country"=>"australia",
"newprice"=>"50",
"breed"=>"gala"),
"orange" => array("country"=>"belgium",
"newprice"=>"30",
"breed"=>"gala"),
);
i am able to loop the first array but how to replace the price of first array(while in foreach loop) to newprice with condition the category(orange/apple), country and breed matched second array?
like below result,
gala apple from australia price is RM 50
fuji apple from belgium price is RM 10
Honeycrisp apple from USA price is RM 10
washington apple from canada price is RM 10
gala orange from australia price is RM 10
fuji orange from belgium price is RM 10
Honeycrisp orange from USA price is RM 10
washington orange from canada price is RM 10
To have the desired result, do the following
$groceritems = array(
"apple" => array(
"price"=>"10",
"origin"=>array("australia","belgium","USA","canada"),
"breed"=>array("gala","fuji","Honeycrisp","washington"),),
"orange" => array(
"price"=>"10",
"origin"=>array("australia","belgium","USA","canada"),
"breed"=>array("gala","fuji","Honeycrisp","washington"),
),
);
$grocer= array(
"apple" => array( "country"=>"australia",
"newprice"=>"50",
"breed"=>"gala"),
"orange" => array("country"=>"belgium",
"newprice"=>"30",
"breed"=>"gala"),
);
foreach ($groceritems as $key => $value) {
$origins = $value['origin'];
$breeds= $value['breed'];
foreach (array_combine($origins, $breeds) as $origin=>$breed) {
if(isset($grocer[$key]) && $origin == $grocer[$key]['country'] && $breed == $grocer[$key]['breed'] ){
$price = $grocer[$key]['newprice'];
} else {
$price = $value['price'];
}
echo $breed ." ".$key." from ". $origin ." price is RM ". $price;
echo "<br>";
}
}
I'm looking for a solution to apply a discount to a value based on an foreach loop of items, my main problem is that if the second item meet the requirements it will apply on it too, so what i want is just to apply to the first of the item that has found with the requirement and then pass to other action.
echo '<pre>';
$requeriment = 299;
$items = array(
array(
'id' => 1,
'price' => 199,
'quantity' => 1
),
array(
'id' => 2,
'price' => 399,
'quantity' => 1
),
array(
'id' => 3,
'price' => 199,
'quantity' => 1
)
);
$flag = false;
foreach($items as $item){
$totalItem = $item['price'] * $item['quantity'];
if($totalItem > $requeriment){
if(!$flag){
$flag = true;
echo 'Disc 1% - ' . $item['id'];
echo "<br>";
}else if($flag){
echo 'Disc 2% - ' . $item['id'];
echo "<br>";
}
continue;
}
echo 'Disc 2% - ' . $item['id'];
echo "<br>";
}
//Ok, it found ID 2 with a value bigger than requirement and the job is done.
//Now if trough loop it not found item that meet the requirement
//it need now to sum values to get the required value to meet the requirement
//and apply a 1% the the 2 items that made that sum, then apply 2% to the rest of ids.
Is there a way to to this in the same loop?
$i=0;
foreach $items as $item{
$i++;
$totalItem = $item->price * $item->quantity;
if($totalItem > $requeriment){
//Apply a discount of 1%
if($i==1){
// for discount 1
}elseif($i==2){
// for discount 2
}
}
As same as another discount.
Let's say I have an array like this :
$intarray = array("300","350","399","650","625","738","983","1200","1050");
how can I display this array to user like this :
Price
_________________
[] 300 - 699 (5)
[] 700 - 999 (2)
[] 1000 - 1500 (2)
Details :
as in the example I wanted to show the user not the whole elements but option to select between them by giving limits low and max limits. So if user select 300 - 699, page display the results between 300-699
That $intarray is generated dynamically so some code must handle the splitting. Array can
have more elements. What I want is divide the numbers like 5 range options to show the user.
Having in mind my comment, I assume you want to count particular ranges.
<?php
$intarray = array("300","350","399","650","625","738","983","1200","1050");
//echo "[] ". $intarray[0]. " - " .$intarray[4][0]."99"; # that was in my comment
$ranges = array(
0 => array(
'min' => 300,
'max' => 699
),
1 => array(
'min' => 700,
'max' => 999
),
2 => array(
'min' => 1000,
'max' => 1500
)
);
foreach ($intarray as $val) {
for ($i = 0; $i < count($ranges); $i++){
if ($val >= $ranges[$i]['min'] && $val <= $ranges[$i]['max']) {
$range_values[$i][] = $val;
}
}
}
var_dump($range_values);
array (size=3)
0 =>
array (size=5)
0 => string '300' (length=3)
1 => string '350' (length=3)
2 => string '399' (length=3)
3 => string '650' (length=3)
4 => string '625' (length=3)
1 =>
array (size=2)
0 => string '738' (length=3)
1 => string '983' (length=3)
2 =>
array (size=2)
0 => string '1200' (length=4)
1 => string '1050' (length=4)
You can use count() in order to display the thing in the brackets
for ($i = 0; $i < count($ranges); $i++) {
$max = max($range_values[$i]);
echo "[] " . min($range_values[$i]) . " - " . $max[0]."99" . " (". count($range_values[$i]).")" . "<br />";
}
[] 300 - 699 (5)
[] 738 - 999 (2)
[] 1050 - 199 (2)
Or just display the ranges (as it was the desired output?) and count($ranges_values) current iteration
for ($i = 0; $i < count($ranges); $i++) {
echo "[] " . $ranges[$i]['min'] . " - " . $ranges[$i]['max'] . " (" . count($range_values[$i]) . ")" . "<br />";
}
[] 300 - 699 (5)
[] 700 - 999 (2)
[] 1000 - 1500 (2)
Try
$intarray = array("300","350","399","650","625","738","983","1200","1050");
sort($intarray);
$result=array();
foreach($intarray as $key=>$val){
switch($val){
case ($val > 300 && $val < 699):
$result[0][] = $val;
break;
case ($val > 700 && $val < 999):
$result[1][] = $val;
break;
case ($val > 1000 && $val < 1500):
$result[2][] = $val;
break;
}
}
demo here
You can do a function that prints and counts the numbers in your range
public function printInRanges($startRange, $endRange)
{
$count = 0;
foreach($element in $array)
{
if($element>=$startRange && $element<=$endRange)
count++;
}
echo $startRange."-".$endRange."(".$count.")";
}
And than you can call this function with whatever ranges you want
Last Edit
if you want to do this for all your array, get your first element value (array[0]) and last element value, and call the function from a loop
$startValue = array[0];
while($startValue + 500 < $endValue)// 500 being the value between ranges like 0-500,500-1000,1000-1500
{
printInRanges($startValue ,$startValue +500);
$startValue+=500;
}