function to search value inside multidimensional array - php

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

Related

Print price when item is in shoppingcar array

i already have the output of the items and the amount of the item but now i am trying to print out the price of the item but it is not working.
This is the page of the shoppingcar
<?php
//script opdracht1a.php
session_start();
// lees dit als: in de winkelwagen zitten 3 boeken en 1 pet
$_SESSION['winkelwagen'] = array( 'boek' => 3, 'pet' => 1 );
?>
And at this page i want to print out the products and amounts of 'winkelwagen' but next to it i also need to print out the prices of the products of array $aPrijzen
Here is the second code of the other page
session_start();
$aPrijzen = array ('boek' => 5, 'pet'=> 8 , 'jas' => 10, 'jurk' => 22);
$winkelwagen = $_SESSION['winkelwagen'];
foreach($winkelwagen as $key => $value)
{
for($i = 0; $i < count($aPrijzen); $i++)
if($value == $aPrijzen)
{
echo $key.' '.$value.' '.$aPrijzen[i].'<br>';
}
}
Your code can be simplified to:
$aPrijzen = array ('boek' => 5, 'pet'=> 8 , 'jas' => 10, 'jurk' => 22);
foreach($_SESSION['winkelwagen'] as $key => $value)
{
if(isset($aPrijzen[$key]))
{
echo $key.' '.$value.' '.$aPrijzen[$key].'<br>';
}
}

How can I output specific data from an associative array in PHP with foreach

My associative array:
$products = array();
$products[101] = array(
"name" => "Red Shirt",
"img" => "img/shirts/shirt-101.jpg",
"price" => 18
);
$products[102] = array(
"name" => "Black Shirt",
"img" => "img/shirts/shirt-102.jpg",
"price" => 20
);
$products[103] = array(
"name" => "Blue Shirt",
"img" => "img/shirts/shirt-103.jpg",
"price" => 20
);
So lets say I wanted to output the name of ALL products array like so:
Red Shirt, Black Shirt, Blue Shirt
how can I achieve that with a foreach loop? I have tried to output only a specific key from all arrays at once but I cannot seem to do it without outputting all the keys.
Also lets say I wanted to just output the "price" of a certain array like $products[103] how can I achieve that?
Thank you!
you can use below code, with using foreach
foreach($products as $pro)
{
echo $pro['name'];
}
above code will print only name key of the product array
to get price of $product['103'] you can use like below code
foreach ($products as $key => $value)
{
if ($key == '103')
{
echo $pro['price'];
}
}
EDIT : to get array of names
$names = array();
foreach ($products as $pro)
{
$names[] = $pro['name'];
}
print_r($names);
it will return
Array ( [0] => Red Shirt [1] => Black Shirt [2] => Blue Shirt )
let me know if this helped you
Simple,Use like this
foreach($products as $product){
echo $product['name'];
}
Try this
foreach($products as $key => $val) {
// For name
echo $val['name'];
// For specific product price
if($key == 103) {
echo $val['price'];
}
}
Let me know, if there is any issue.
Try the following code (This will cover all scenarios):
function getMyArray($key, $arr = array()){
$result = array();
foreach($arr as $arrVal){
$result[] = $arrVal[$key];
}
return implode(", ", $result);
}
echo getMyArray('name', $products); // Red Shirt, Black Shirt, Blue Shirt
echo getMyArray('img', $products); //path1, path2, path3
echo getMyArray('price', $products); // 18, 20, 20
If you want some particular value:
echo $products[103]['price']; // 20
Try this one
foreach ($products as $prd) {
echo $prd['name'];
}
$productNames = array();
foreach($products as $key=>$product) {
$productNames[] = $product['name'];
}
//all names with comma
echo implode(',',$productNames);
echo "\n";
//only price of $products[103]
echo $products[103]['price'];
Result:
Red Shirt, Black Shirt, Blue Shirt
20
you will get exact the same out put as you wished by this code
foreach($products as $key=>$result)
{
echo $result['name'].', ';
}
Out put :
Red Shirt, Black Shirt, Blue Shirt

How to keep the ending 0s when reporting money [duplicate]

This question already has answers here:
Show a number to two decimal places
(25 answers)
Closed 8 years ago.
Hello I have a basic php script which is used to display the price of a group of items in an array. The array has 3 pieces of information: name, price, and sku. The price could be set to something like 99.95, 12.95, 10.50 or just 5.00. Everything seems to work well so far, but when I try to report any price like 5.00 or 10.00 (whole dollar amounts) it just truncates the ending .00, which isnt exactly a problem but I would rather have it display the trailing zeros so everything looks nice and similar. Here is the code for the array/reporting loop:
$items = Array
(
"0"=> Array
(
"name" => $_SESSION['itemname-mo'],
"price" => $_SESSION ['price-mo'],
"sku" => $_SESSION ['sku-mo']
),
"1" => Array
(
"name" => $_SESSION['itemname-addon'],
"price" => $_SESSION ['price-addon'],
"sku" => $_SESSION ['sku-addon']
),
"2" => Array
(
"name" => $_SESSION['itemname-addon1'],
"price" => $_SESSION ['price-addon1'],
"sku" => $_SESSION ['sku-addon1']
),
"3" => Array
(
"name" => $_SESSION['itemname-addon2'],
"price" => $_SESSION ['price-addon2'],
"sku" => $_SESSION ['sku-addon2']
)
);
$a_length = count($items);
for($x = 0; $x<$a_length; $x++){
$total +=$items[$x]['price'];
}
echo "<div class=\"well\">";
for($i = 0; $i < $a_length; $i++){
$name = $items[$i]['name'];
$price = $items[$i]['price'];
$sku = $items[$i]['sku'];
displaycart($name,$price,$sku);
}
echo "<br />
Sub Total:
$$total";
echo "</div>";
function displaycart($name,$price,$sku){
if($name != null || $price != null || $sku != null){
echo "$name: $$price ($sku) <br />";
}
else{ echo "";}
}
See number_format.
number_format($number, 2, '.', '');
Use number_format when echo'ing.

get index of array with condition

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

Arrange the array in table format

This is my array and I want to set this array in table format and I want to set first row as show below:
$_tierPrices = Array
(
Array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
Array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
Array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
Array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
I want to set this array value in table format as shown below
This is my table row:
4 | 12 | 20 | 40 |
I need this:
4 - 11 | 12 - 19 | 20 - 39 | 40+ |
Please advise.
Try this:
Tier Price Array
<?php
$_tierPrices = array (
array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
?>
Tier Price Table
<table>
<tr><td>Header</td></tr>
<?php $_qtyRow = '<tr>'; ?>
<?php $_priceRow = '<tr>'; ?>
<?php $_saveRow = '<tr>'; ?>
<?php
$size = count($_tierPrices);
foreach($_tierPrices as $index => $_tierPrice) {
if($index < $size-1) {
$_qty = $_tierPrice['price_qty'] . ' - ' . ($_tierPrices[$index+1]['price_qty'] - 1);
} else {
$_qty = $_tierPrice['price_qty'] . '+';
}
$_qtyRow .= '<td>'.$_qty.'</td>';
$_priceRow .= '<td>'.$_tierPrice['price'].'</td>';
$_saveRow .= '<td>'.$_tierPrice['savePercent'].'</td>';
}
$_qtyRow .= '</tr>';
$_priceRow .= '</tr>';
$_saveRow .= '</tr>';
echo $_qtyRow;
echo $_priceRow;
echo $_saveRow;
?>
<tr><td>Footer</td></tr>
</table>
I hope this will help.
I don't know what you have in $_tierPrices so i am giving you an example by for some other data.
$arr = array('4','12','20','40'); //suppose you have array like this
$end = end($arr); //We need to find last element of the array to show like 40+
for($i=0;$i<count($arr);$i++){
if($arr[$i] != $end){
echo $arr[$i]."-".($arr[$i+1]-1)." | ";
} else{
echo $arr[$i]."+";
}
}
Output will be like
4-11 | 12-19 | 20-39 | 40+
<?php
echo "<table><tr>";//opening the table
$first_iteration = FALSE;
foreach ($_tierPrices as $value)
{
if (!$first_iteration)//code that only runs on the first iteration
{
$first_iteration = TRUE;
$buffer_value = $value;
}
else {//code that runs after the first iteration
$buff = ((integer)$value)-1;//calculation1 value previous
$output = $buffer_value."-".$buff;
echo "<td>".$output."</td>";
$buffer_value = $value;
}
}
echo "<td>".$buffer_value."+</td>";
echo "</tr></table>";//closing the table
?>
let me know if that worked for you :)

Categories