show difference between of two price list - php

I have history list of product price(order by created_at) like this:
Array
(
[0] => stdClass Object
(
[id] => 1
[product_id] => 49
[price] => 14520000.0000
[created_at] => 1592501154
)
[1] => stdClass Object
(
[id] => 2
[product_id] => 49
[price] => 14000000.0000
[created_at] => 1592587554
)
[2] => stdClass Object
(
[id] => 4
[product_id] => 49
[price] => 14800000.0000
[created_at] => 1592673954
)
[3] => stdClass Object
(
[id] => 5
[product_id] => 49
[price] => 10000000.0000
[created_at] => 1592760354
)
[4] => stdClass Object
(
[id] => 6
[product_id] => 49
[price] => 14000000.0000
[created_at] => 1592846754
)
[5] => stdClass Object
(
[id] => 7
[product_id] => 49
[price] => 14000000.0000
[created_at] => 1592933154
)
[6] => stdClass Object
(
[id] => 8
[product_id] => 49
[price] => 14000000.0000
[created_at] => 1593019554
)
)
Now for show data in table I listed price using foreach method like this:
<?php foreach($product_prices_list as $product_price_list):?>
<tr>
<td><?= esc($product_price_list->created_at);?></td>
<td class="text-center"><?= esc(number_format($product_price_list->price));?></td>
<td class="text-center"></td> //show difference between of two price
</tr>
<?php endforeach;?>
I can see true output in table but I need to show difference between of two price in the third column like this picture:
how do can i show difference between of two price in my list?!

You just need to compare the current price property to the price from the previous object in the array?
Something like this should work:
<?php foreach($product_prices_list as $key => $product_price_list):?>
<tr>
<td><?= esc($product_price_list->created_at);?></td>
<td class="text-center"><?= esc(number_format($product_price_list->price));?></td>
<td class="text-center"><?= (!empty($product_prices_list[$key - 1])) ? $product_prices_list[$key + 1]->price - $product_price_list->price: 0; ?></td> //show difference between of two price
</tr>
<?php endforeach;?>

If you are running MySQL 8.0, you can compute this information directly in the database using window functions:
select
t.*,
price
- lag(price, 1, price) over(partition by product_id order by created_at)
as price_diff
from mytable t
This adds one more column to your resultset, that contains the difference between the current price and the previous price of the same product.

Related

How i display the json array data from api [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
Below is my data get from API , I try to display the shopId, Shopname and shopcode but failed.Any one can help me solve this problem ? I am using the PHP to write the script and get API data.Below is my script to get API data.
<?php
$get = file_get_contents("http://api.meirenji.cn/api/xxxxxxxxxxx");
$json = json_decode($get);
$shop_id = $json->content->shopId;
echo "Shop ID : ".$shop_id."";
?>
Below is the data that i get from API, it have multiple array data, i nee get data shopId, Shopname,shopcode
stdClass Object
(
[status] => 0
[msg] => succes
[content] => Array
(
[0] => stdClass Object
(
[shopId] => 6674
[shopname] => SP
[shopcode] => 38862185
[type] => shop
[flag] => 1
)
[1] => stdClass Object
(
[shopId] => 6498
[shopname] => Adidas
[shopcode] => 74812597
[type] => shop
[flag] => 1
)
[2] => stdClass Object
(
[shopId] => 6498
[shopname] => Nike
[shopcode] => 98741852
[type] => shop
[flag] => 1
)
[3] => stdClass Object
(
[shopId] => 6501
[shopname] => Puma
[shopcode] => 13847915
[type] => shop
[flag] => 1
)
[4] => stdClass Object
(
[shopId] => 6509
[shopname] => Adidas NEO
[shopcode] => 26700485
[type] => shop
[flag] => 1
)
[5] => stdClass Object
(
[shopId] => 6865
[shopname] => Testing Unit
[shopcode] => 23891935
[type] => shop
[flag] => 1
)
[6] => stdClass Object
(
[shopId] => 9661
[shopname] => UNDER ARMOR
[shopcode] => 88741294
[type] => shop
[flag] => 1
)
)
)
To get shopname and shopcode from your response object, you've to loop over your content like this way using foreach(),
foreach($json->content as $key=>$row){
echo "shopname = $row->shopname and shopcode = $row->shopcode". PHP_EOL;
}
DEMO: https://3v4l.org/tWqt7

PHP/Guzzle Target parent element

I have an app using guzzle/php to make requests to a rest service.
When it yields a response, it includes nested arrays and objects:
[exampleBalances] => Array (
[0] => stdClass Object (
[balance] => 6
[name] => Prize One
[prizeCode] => 38
)
[1] => stdClass Object (
[balance] => 5
[name] => Prize Two
[prizeCode] => 20
)
[2] => stdClass Object (
[balance] => 4
[name] => Prize Four
[prizeCode] => 39
)
)
Until now Ive been pulling the value based on the order:
$prizeThree = $response->exampleBalances['3']->balance;
However, the service wont display any 'prizes' if the customer has 0, so the example above would no longer be accurate if a new item was added:
[exampleBalances] => Array (
[0] => stdClass Object (
[balance] => 6
[name] => Prize One
[prizeCode] => 38
)
[1] => stdClass Object (
[balance] => 5
[name] => Prize Two
[prizeCode] => 20
)
[2] => stdClass Object (
[balance] => 8
[name] => Prize Three
[prizeCode] => 54
)
[3] => stdClass Object (
[balance] => 4
[name] => Prize Four
[prizeCode] => 39
)
)
Is there a way to target the correct element, without using the order that it appears in the response?
I could not find any documentation, but its difficult to convey the issue. I was thinking there may be someway to create a condition to check an elements inner values (preferably the 'prize code') Any help would be greatly appreciated.
In PHP 5.5.0 or newer, you can use the array_column() function to do this search:
$index = array_search($prizeCodeSearch, array_column($exampleBalances, 'prizeCode'));
$element = $exampleBalances[$index];

What is the correct way to write an SQL statement to push data rows for this array?

I am trying to push array data to a MySQL database using foreach(). I'm quite a novice at PHP & mysql, so been working through parsing this data to PHP from an Ajax script, now just need to manipulate the data.
What is the correct syntax to push this data into SQL so that each dataset in the array goes to a seperate row?
i am trying to use foreach, but the complexity is that the array itself can change in size and the second complexity is that the data itself may be refreshed (i.e same id new values on a new day), so I want to build in some intelligence to update info not just append; and also to backup old data to another table.
is this syntax correct?
$sql = "INSERT INTO table1 (col1, col2) VALUES ";
foreach($rows as $i=>$row) {
if ($i>0) {
$sql .= sprintf(",(%s,%s)", $row["col1_value"], $row["col2_value"]);
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
}
mysql_query($sql);
The data in the array is as follows - this is only part of a multidimensional array, but I have figured out how to manipulate the rest of the array to my needs.
The only other thing I need to do is figure out a way to take the coords field and manipulate it as follows
Extract x & y data from coords
Multiple x & y by 600/386
Reverse x & y and take the first digit of each coordinate to create a new value y[1]x[1].
For this I tried just on the first data set, as follows, but I am inexperienced in data handling on PHP. Pretty sure it is wrong.
$testcoords = $_POST['data'][0]['coords'];
list($x,$y) = explode(“:”,str_replace(“’”,“”,$testcoords));
$xtrans = number_format($x*600/386,$decimals=null);
$ytrans = number_format($y*600/386,$decimals=null);
$cont = “C”.$ytrans[0].$xtrans[0]
So to summarize, three questions
How do I transfer data into a table, with rows for each individual dataset in the [data] array?
How do overwrite and archive any existing values in the table rather than simply concatenating?
How do I manipulate one specific string to return a custom variable as defined above?
[data_type] => city
[data] => Array
(
[0] => Array
(
[id] => 16515340
[owner_id] => 3475
[owner] => Player1
[coords] => '268:252
[name] => AC2013
[score] => 11863
[city_type] => castle
[location] => land
)
[1] => Array
(
[id] => 16515335
[owner_id] => 3475
[owner] => Player1
[coords] => '263:252
[name] => AC2013
[score] => 7
[city_type] => castle
[location] => water
)
[2] => Array
(
[id] => 17891610
[owner_id] => 3523
[owner] => Player2
[coords] => '282:273
[name] => City of Repoman9900
[score] => 1978
[city_type] => castle
[location] => water
)
[3] => Array
(
[id] => 10616856
[owner_id] => 73
[owner] => Player2
[coords] => '024:162
[name] => 1killer
[score] => 1308
[city_type] => castle
[location] => water
)
[4] => Array
(
[id] => 10813465
[owner_id] => 2862
[owner] => Player3
[coords] => '025:165
[name] => City of vuvuzea991
[score] => 1091
[city_type] => castle
[location] => land
)
[5] => Array
(
[id] => 17367317
[owner_id] => 84
[owner] => Player4
[coords] => '277:265
[name] => Dreadland
[score] => 776
[city_type] => castle
[location] => water
)
[6] => Array
(
[id] => 2162850
[owner_id] => 2989
[owner] => Player5
[coords] => '162:033
[name] => City of Dinoeyez
[score] => 157
[city_type] => castle
[location] => water
)
[7] => Array
(
[id] => 2818192
[owner_id] => 556
[owner] => Player6
[coords] => '144:043
[name] => City of wildfire123
[score] => 7
[city_type] => castle
[location] => water
)
)
[sender] => Array
(
[world] => Array
(
[id] => 232
[name] => Server 4
[number] => NaN
)
[alliance] => Array
(
[id] => 2
[name] => Alliance2
)
[player] => Array
(
[id] => 98
[name] => SuperUser
)
[browser] => Array
(
[type] => Chrome
[version] => 25.0.1364.160
)
[aix_version] => 1.00
)
)
The problems I see:
foreach($rows as $i=>$row) {
$sql = "INSERT INTO table1 (col1, col2) VALUES "; //reinitialize here.
if ($i>0) { //Why have the if statement, the results of the conditions are the same.
$sql .= sprintf("('%s','%s')", $row["col1_value"], $row["col2_value"]); //add quotation marks for string values, remove the comma.
} else {
$sql .= sprintf("(%s,%s)", $row["col1_value"], $row["col2_value"]);
}
mysql_query($sql); //execute the statement here.
}
Your other questions:
How do overwrite and archive any existing values in the table rather than simply concatenating?
To overwrite you do an update statement, the MySql website gives hints to syntax.
To archive, you will need to create an archive table that is pretty much a duplicate of the table being archived and insert/update that table.
In this context, I am not sure what you mean by concatenation, it does not really apply to databases that are normalized.
How do I manipulate one specific string to return a custom variable as defined above?
Ah gonna skip that one, it is a lot to ask in one post.

Codeigniter: Referencing a specific array index returned in model result

I'm still trying to wrap my head around passing db query results from a model back to controller and finally to a view. I seem to be getting the data to the right place, I'm just not sure how to best access the resulting array of objects in the view.
Specifically, I'm trying to query my db for the most recent 7 distinct dates that someone has submitted a link. I get back an array of dates, and then for each of those dates I do a query for all links submitted on that date and store the results in an array. Then in the view, for each of those distinct dates, I show a header (the date), immediately followed by the links associated with it.
The array that come from my distinct date query ($link_headers):
Array (
[0] => stdClass Object([added_date] => 2011-08-11)
[1] => stdClass Object([added_date] => 2011-05-03)
[2] => stdClass Object([added_date] => 2011-04-21)
[3] => stdClass Object([added_date] => 2011-04-10)
[4] => stdClass Object([added_date] => 2011-03-04)
[5] => stdClass Object([added_date] => 2011-02-28)
[6] => stdClass Object([added_date] => 2011-02-22)
)
The array that comes from my query for actual links submitted ($links_result):
Array
(
[0] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1178
[link_url] => http://www.amazon.com/Silicone-Rubber-CASSETTE-Design-IPHONE/dp/B004YDJWOY
[link_name] => Silicone Skin BLACK CASSETTE TAPE
[link_notes] => iPhone case... probably won't fit in my dock.
[added_date] => 2011-08-11
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[1] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1177
[link_url] => http://snorby.org/
[link_name] => Snorby - Snort front-end
[link_notes] =>
[added_date] => 2011-05-03
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[2] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1176
[link_url] => http://www.nytimes.com/2011/04/17/business/17excerpt.html?_r=4&pagewanted=1&ref=business
[link_name] => Corner Office - The 5 Habits of Highly Effective C.E.O.s
[link_notes] => Sounds a lot like what Nathanial said...
[added_date] => 2011-04-21
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[3] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1175
[link_url] => http://chezlarsson.com/myblog/2010/06/panduro-concrete-challenge-3.html
[link_name] => Concrete book-ends
[link_notes] => Cool look...
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 4
[public] => 1
)
[1] => stdClass Object
(
[user_id] => 2
[link_id] => 1174
[link_url] => http://themeforest.net/item/reciprocity-photo-blog-gallery/154590
[link_name] => Site Templates - Reciprocity - Photo Blog
[link_notes] =>
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 5
[public] => 1
)
)
[4] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1173
[link_url] => http://lifehacker.com/#!5771943/the-always-up+to+date-guide-to-jailbreaking-your-ios-device
[link_name] => The Always Up-to-Date Guide to Jailbreaking Your iOS Device
[link_notes] =>
[added_date] => 2011-03-04
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[5] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1172
[link_url] => http://lifehacker.com/#!5754463/how-to-jailbreak-your-ios-421-device
[link_name] => How to Jailbreak Your iOS 4.2.1 Device
[link_notes] =>
[added_date] => 2011-02-28
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[6] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1171
[link_url] => http://www.bitplumber.net/2010/10/a-cassandra-hardware-stack-dell-c1100s-ocz-vertex-2-ssds-with-sandforce-arista-7048s/
[link_name] => A Cassandra Hardware Stack
[link_notes] =>
[added_date] => 2011-02-22
[flag_new] => 1
[rating] => 3
[public] => 1
)
)
)
... all seems fine enough. But my problem comes from my view, where I'm trying to build the HTML as described above. A simplified view of the code I'm trying to get to work is as follows:
foreach ($link_headers as $header) {
echo "INDEX: ". $links_headers .", ADDED DATE: ". $header->added_date ."<BR>";
foreach ($links_result[$link_headers] as $result){
echo $result->added_date ."<BR>";
echo $result->link_name ."<BR><BR>";
}
}
So, I'm trying to use the index of the first one to tell my foreach loop which index of the second array to loop through and get the content. Clearly I'm misusing the $links_result[$link_headers] variable(s) but I left it in to show what I was trying to do.
Any help is very much appreciated!
Michael
I dont use CodeIgniter but whether within th framework or from PHP i would just grab it all in one go and then the issue with the indexes becomes moot:
SELECT * FROM model_table mt WHERE mt.added_date IN (
SELECT DISTINCT md.added_date from model_table md
ORDER BY md.added_date DESC
LIMIT 7
) ORDER BY mt.added_date DESC
That should get you an array of models ordered by date limted to the 7 most recent dates. So then its just a matter of choosing when to display a header:
$current = null;
foreach($links as $link) {
if($link->added_date !== $current) {
// show the header and set current to the current date
$current = $link->added_date;
echo 'HEADER: Added on ' . $current . '<br />';
}
echo $row->added_date ."<BR>";
echo $row->link_name ."<BR><BR>";
}

Store into a database table as row the query result

query result
Array
(
[0] => stdClass Object
(
[ingredientID] => 2
[code] => Bf
[description] => 1st Class Flour
[volume] => 8268
[price] => 750
[amount_gram] => 0.02980
[status] => Inactive
[uom_id] => 1
[flour] => Yes
)
[1] => stdClass Object
(
[ingredientID] => 3
[code] => Sf
[description] => 3rd Class Flour
[volume] => 18490
[price] => 635
[amount_gram] => 0.02540
[status] => Inactive
[uom_id] => 5
[flour] => Yes
)
..........
I want to store this results into another table as row inventory.
the table will look like this:
ID inventory
1 (the result)
2 (another result)
And after I will query it back again so that I can display the result.
here's what I have done lately.
store:
//getting the result
$inv = $this->db->get_from('table','id'=>'1')->row();
<input type="hidden" name="inventory" value="<?php print_r($inv)?>">
//storing in the new table
$this->db->insert('table2',array('inventory'=>$this->input->post('inventory')));
getting:
$inventory = $this->db->get_where('table2',array('ID'=>'1'))->row_array();
//result
array
(
[ID] => 1
[inventory] =>
array
(
[0] => stdClass Object
(
[ingredientID] => 2
...... and so on
I want to display everything in the array['inventory'] which is an array of objects.
I've done this
foreach($arr['inventory'] as $invent):
echo $invent['ingredientID'];
but there's an error in the foreach part.
error: Invalid argument supplied for foreach()
What should i do?
endforeach;
assuming:
$results = $this->db->get_where('table2',array('ID'=>'1'))->row_array();
you should use this to print it
foreach($results['inventory'] as $inventory)
{
print_r($inventory->ingredientID);
}

Categories