How to store array value and add another value php - php

I'm trying to write the product name and quantity from a given order, then read from the next order and add to the array but the final array only stores the value from the last loope
I don't know what I'm doing wrong, I also tried array_push
I would like to count the number of units sold and display as follows for all orders:
Product A - 50 pieces
Product B - 30 pieces, etc.
foreach ($order_id as $order_ids) {
//echo '</br>' . $vendor_id . ' ' . $vendor_mail . ' ' . $vendor_name . '</br>';
$orderID = $order_ids->order_id;
$order_date = $order_ids->date_created;
$single_order = wc_get_order($orderID);
echo '</br>';
echo __('ID zamówienia: ') . $orderID . '<br>';
echo __('Data zamówienia: ') . $order_date . '<br>';
$product_quantity = array();
$product_name = array();
$single_order_array=array();
$array_merge=array();
foreach ($single_order->get_items() as $item) {
echo __('Nazwa produktu: ') . $item->get_name() . '<br>';
echo __('Ilość: ') . $item->get_quantity() . '<br><br><br>';
$product_quantity[] = $item->get_quantity();
$product_name[] = $item->get_name();
$single_order_array=array_combine($product_name, $product_quantity);
}
echo '</br>TABLICA POJEDYNCZEGO ZAMOWIENIA: </br>';
print_r($single_order_array);
echo '</br></br>';
$array_merge=array_replace_recursive($single_order_array, $array_merge);
}
echo '</br>TABLICA CAŁEGO WENDORA : </br>';
print_r($array_merge);
echo '</br></br>';
}

Original answer
According to your code $single_order_array will be overwritten within each loop of foreach ($single_order->get_items() as $item). So in this array you will get data only for last item from order.
As for usage of array_replace_recursive I can't quite get your idea. BTW how do you get you initial array $order_id?
EDIT
Try this code:
$results=array(); // place this outside all loops
foreach ($order_id as $order_ids) {
//echo '</br>' . $vendor_id . ' ' . $vendor_mail . ' ' . $vendor_name . '</br>';
$orderID = $order_ids->order_id;
$order_date = $order_ids->date_created;
$single_order = wc_get_order($orderID);
echo '</br>';
echo __('ID zamówienia: ') . $orderID . '<br>';
echo __('Data zamówienia: ') . $order_date . '<br>';
$product_quantity = array();
$product_name = array();
$single_order_array=array();
foreach ($single_order->get_items() as $item) {
echo __('Nazwa produktu: ') . $item->get_name() . '<br>';
echo __('Ilość: ') . $item->get_quantity() . '<br><br><br>';
$product_quantity = $item->get_quantity();
$product_name = $item->get_name();
$single_order_array[]=array($product_name => $product_quantity);
}
echo '</br>TABLICA POJEDYNCZEGO ZAMOWIENIA: </br>';
print_r($single_order_array);
echo '</br></br>';
foreach ($single_order_array as $product=>$quantity){
if (array_key_exists($product, $results)){
$results[$product]+=$quantity;}
else {$results += array ($product=>$quantity);
}
}
}
echo '</br>TABLICA CAŁEGO WENDORA : </br>';
print_r($results);
echo '</br></br>';
Sould work but not tested as I have no idea how orders' data is stored into your input array $order_id.

Your for loop is updating the values. You need to use associative array and store values in it. This will solve your problem.
$data = [];
for($i =0; $i<sizeof($items); $i++)
{
$data[$i]['item_value_1'] = $items[$i]->item_value_1;
$data[$i]['item_value_2'] = $items[$i]->item_value_2;
$data[$i]['item_value_3'] = $items[$i]->item_value_3;
}

Related

How to get array from API

I want to get the episode number and Released from
http://www.omdbapi.com/?t=the+walking+dead&season=6&r=json
but I don't know how to extract arrays from the api.
Can someone help me?
My code is:
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
}
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json = file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details = json_decode($json);
if ($details->Response == 'True') {
echo 'There are ' . count($details->Episodes) . ' episodes<br />';
foreach ($details->Episodes as $key => $episode) {
echo 'Episode criteria number is ' . ($key + 1) . '<br />';
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released: ' . $episode->Released . '<br />';
}
}
<?php
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
foreach ($episodios as $episode) {
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released Date: ' . $episode->Released . '<br />';
}
}
?>

PHP: how to make a sum inside a "for each" cycle?

I've made a foreach loop that print some variables found in an xml file:
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
}
I would like to get the sum of all the "prices" shown. How can i do?
Just have a variable add up those values as you iterate:
$total = 0; // start with zero
foreach ($xml->result->rowset->row as $row)
{
$total += $row["price"]; // add price to total
echo $row["price"] . " " . $row["product"] . "</br>";
}
echo $total; // echo out total amount
Store the count in a variable:
$total = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "</br>";
$total += $row['price']; // assumed row_price is some integer
}
echo $total;
Simply add it to a new variable:
$sum = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "<br />";
$sum += $row["price"];
}
echo $sum . "<br />";
$sum = 0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum += $row["price"] ;
}
echo $sum ;
isnt that simple ?
$sum=0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum +=$row["price"];
}
echo $sum;
just try this code!!

PHP Array Declaration

for ($k = 0; $k < $count; $k++) {
$master[$k] = $namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k];
}
I'd like to declare a new array and set values from other arrays already declared. I thought I could just loop through the keys and set the values but this doesn't work for me.
Full code below. I'm parsing yellow pages search results and trying to output search results into a csv file. In the code below I removed the loop and only added a few values to the array to make sure my bug wasn't something else.
<?php
// include required functions
include('simple_html_dom.php');
$url = "http://www.yellowpages.com/" . $_POST['city'] . '-' . $_POST['state'] . '-' . $_POST['postalcode'] . '/' . $_POST['category'] . '?g=' . $_POST['city'] . '%2C+' . $_POST['state'] . '+' . $_POST['postalcode'] . '&q=' . $_POST['category'];
// get DOM from URL
$html = file_get_html($url);
// find all business name
foreach($html->find('h3.business-name') as $name)
//echo $name->innertext . '<br />';
$namearray[] = $name->innertext;
// find all business street address
foreach($html->find('span.street-address') as $street)
//echo $street->innertext . '<br />';
$streetarray[] = $street->innertext;
// find all business city
foreach($html->find('span.locality') as $locality)
//echo $locality->innertext . '<br />';
$localityarray[] = $locality->innertext;
// find all business state
foreach($html->find('span.region') as $region)
//echo $region->innertext . '<br />';
$regionarray[] = $region->innertext;
// find all business postal code
foreach($html->find('span.postal-code') as $postalcode)
//echo $postalcode->innertext . '<br />';
$postalcodearray[] = $postalcode->innertext;
// find all business phone
foreach($html->find('span.business-phone') as $phone)
//echo $phone->innertext . '<br />';
$phonearray[] = $phone->innertext;
?>
<p>Search results for: <?php echo $_POST['category'] . ' ' . $_POST['city'] . ' ' . $_POST['state'] . ' ' . $_POST['postalcode']; ?></p>
<?php
// Output results
$count = count($namearray);
for ($i = 0; $i < $count; $i++) {
echo $namearray[$i] . '<br />';
echo $streetarray[$i] . '<br />';
echo $localityarray[$i] . ',' . $regionarray[$i] . ' ' . $postalcodearray[$i] . '<br />';
echo $phonearray[$i] . '<br />' . '<br />';
}
$list = array (
array($namearray[0], $streetarray[0], $localityarray[0], $regionarray[0], $postalcodearray[0], $phonearray[0]),
array($namearray[1], $streetarray[1], $localityarray[1], $regionarray[1], $postalcodearray[1], $phonearray[1]),
array($namearray[2], $streetarray[2], $localityarray[2], $regionarray[2], $postalcodearray[2], $phonearray[2]),
array($namearray[3], $streetarray[3], $localityarray[3], $regionarray[3], $postalcodearray[3], $phonearray[3])
);
$fp = fopen('hrpsearch.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Try:
$master = array();
for ($k = 0; $k < $count; $k++) {
$master[$k] = array
( $namearray[$k]
, $streetarray[$k]
, $localityarray[$k]
, $regionarray[$k]
, $postalcodearray[$k]
, $phonearray[$k]
);
}
This will create a new two-dimensional array for you with associated keys for every child array.
Try
for($k = 0; $k < $count; $k++) {
$master[$k] = array(
$namearray[$k],
$streetarray[$k],
$localityarray[$k],
$regionarray[$k],
$postalcodearray[$k],
$phonearray[$k]
);
}
Maybe do you just want to achieve this?
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
I would suggest using instead:
$master[$k]['name'] = $namearray[$k];
$master[$k]['street'] = $streetarray[$k];
...
The retrieval of the data will be more readable.
I think #DaveRandom's answer is what (I imply) you are looking for.
Since a PHP array can be of any type (scalar, array, object, etc.), you need to tell it you are assigning an array with the construct array().
The end result would be:
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
Try this
for ($k = 0; $k < $count; $k++) {
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
}
or is better to create associative array
for ($k = 0; $k < $count; $k++) {
$master[$k] = array('name'=>$namearray[$k],
'street'=>$streetarray[$k],
'city'=>$localityarray[$k],
'region'=>$regionarray[$k],
'postalCode'=>$postalcodearray[$k],
'phone'=>$phonearray[$k]);
}
You also need to check if your array elements are not empty or just put # befor array element like 'name'=>#$namearray[$k]. It will remove any warning if element doesn't exist.

Last iteration of PHP foreach loop code change

I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}
For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}
Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }
Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}
First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}

I have var_dump a variable and it is empty

I want to know the reasons why this variable is passing empty.
<form action="cart.php" method="POST">
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' " /></form>
Can you see $product['name'] how can I print the it's value after extracting it's values in cart.php as
extracts values
list($aDoor, $variety,$productname) = split('_', $_POST['price']);
$aDoor = array();
$variety = array();
$productname= array();
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
}
Now below the foreach loop how can I echo the print of productname once..?
foreach($productname as $name) {
echo $name . '<br />';
}
or if you want to associate the product names with their other values in $aDoor and $variety you could do:
foreach($productname as $index => $name) {
echo 'Name: ' . $name . '<br />';
echo 'Variety: ' . $variety[$index] . '<br />';
echo 'Price: ' . $aDoor[$index] . '<br />';
}
EDIT:
If I can take your comment to mean that all of the names are the same in the $productname array then you can do this instead:
if(count($productname) > 0) {
echo 'Product Name: ' . $productname[0] . '<br />';
foreach($variety as $index => $name) {
echo $name . ': $' . $aDoor[$index] . '<br />';
}
}
Now below the foreach loop how can I
echo the print of productname once..?
print_r ($productname);
But if you want to see each value of product name inside the loop:
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
echo $c . '<br />'; // show product name
}
Also, i don't see your echoing this line of code with php:
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' " /></form>
in which case this is not how to show value in above line:
value="' . $variety['price'].'_'. $variety['variety']. '_'. $product['name'] . ' "
instead you need to wrap it in php tags:
value="<?=$variety['price'].'_'. $variety['variety']. '_'. $product['name']?>"
As I stated in another of your questions, you cannot use split() on an array. You're forcing PHP to treat $_POST['price'] as an array by naming it "price[]" in your form. WHen you split on an array:
$arr = array('a', 'b', 'c');
list($a, $b, $c) = split($arr);
you end up with the following:
$a = 'Array';
$b = NULL;
$c = NULL;
You will have to do the following:
list($aDoor, $variety,$productname) = explode('_', $_POST['price'][0]);
^^^ (note the array notation)
You're also not creating a $product variable in your extractions cript. You are creating a $productname array, but $productname is not the same as $product['name']

Categories