Counting the quantity by using the Steam Api - php

I was messing around with the steam API and I found out that I was not able to get the quantity of my items. Lets say I have item A 2 times, it does not show the picture just 1 time with the quantity set to "2", but instead it shows the item twice with the quantity set to 1.
This is the part I use to get the inventory.
$backpackURL = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" . $APIkey . "&SteamID=" . $profile . "&format=json";
$schemaURL = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=" . $APIkey . "&language=en";
$userBackpack = json_decode(file_get_contents($backpackURL), true);
$itemSchema = json_decode(file_get_contents($schemaURL), true);
$backpack_items = $userBackpack['result'];
$schema_items = $itemSchema['result'];
And here I list all the items:
foreach($backpack_items['items'] as $ind=>$backpack_items){
$id = $backpack_items['id'];
$defindex = $backpack_items['defindex'];
$name = getItemName($schema_items, $defindex, $image_url);
$quantity = $backpack_items['quantity'];
$inventory = $backpack_items['inventory'];
echo '
$tmp[] = $backpack_items; print_r($tmp)
';
}

Since there is no ID to see if there are any duplicates, you can try to merge them by name.
By reading this code, it first creates a copy of the main array.
I loop over the main array, then again over the copy. So for each value of the main array, a complete cycle of the array is done again for values to compare against.
Since it is expected that there is atleast 1 name, I don't unset immidiatly, but only after another result is found, hence the $b.
It's quantity is increased if a dupe is found, on the key of the main loop.
$copy = $backpack_items['items'];
foreach($backpack_items['items'] as $k => $v){
$b = false;
$s = '';
$n = getItemName($schema_items, $v['defindex'], $s);
foreach($copy as $k2 => $v2){
if($n == getItemName($schema_items, $v2['defindex'], $s)){
if(!$b){
$b = $k;
} else {
unset($backpack_items['items'][$k2]);
$backpack_items['items'][$k]['quantity'] += 1;
}
}
}
}
// Now use your original loop, and the dupes should be removed.

Related

Trying to see if a value from one array exist in another array using PHP

I have these two arrays like so -
$props = json_decode('[{"proposal":"proposal 1", "owner":"tom", "lock_time":1639440607},{"proposal":"proposal 2", "owner":"bob", "lock_time":1639455554}]', true);
$votes = json_decode('[{"vote":"approve", "vote-owner":"tom", "prop-id":1639440607},{"vote":"reject", "vote-owner":"bob", "prop-id":1639455554},{"vote":"reject", "vote-owner":"tom", "prop-id":1639440607}]', true);
When I loop through array one and array two I count the votes for each proposal. I would like to know when a user has voted on each proposal as well. I cant seem to get it to work as expected Here is my PHP loop -
$owner = 'tom';
foreach($props as $props){
$lock_time = $props['lock_time'];
$my_proposal = $props['proposal'];
$owner = $props['owner'];
$approvals=0;
$rejects=0;
$is_voted = '';
foreach($votes as $votes){
$id = $votes['prop-id'];
$vote = $votes['vote'];
$vote_owner = $votes['vote-owner'];
if($lock_time == $id){
if($owner == $vote_owner){
$is_voted = 'true';
}else{
$is_voted = 'false';
}
if($vote == 'approve'){
$approvals++;
}elseif($vote == 'reject'){
$rejects++;
}
}
}
echo $my_proposal.' Voted= '.$is_voted;
}
I suspect because im checking inside the votes loop and displaying outside the vote loop but am unsure of the right way to do this.
Current outcome is all false, expected outcome would be Tom voted on 2 of the 3 proposals so 2 true and 1 false;
Heres a demo - http://sandbox.onlinephpfunctions.com/code/78d28ac1c251b0d006bfda6c2722b156bfaed32f

Distribute options uniquely algorithm

I have a 2 dimensional array. Each subarray consists out of a number of options. I am trying to write a script which picks one of these options for each row. The chosen options have to be unique. An example:
$array = array(
1 => array(3,1),
2 => array(3),
3 => array(1,5,3),
);
With a solution:
$array = array(
1 => 1,
2 => 3,
3 => 5,
);
I have finished the script, but i am not sure if it is correct. This is my script. The description of what i am doing is in the comments.
function pickUnique($array){
//Count how many times each option appears
$counts = array();
foreach($array AS $options){
if(is_array($options)){
foreach($options AS $value){
//Add count
$counts[$value] = (isset($counts[$value]) ? $counts[$value]+1 : 1);
}
}
}
asort($counts);
$didChange = false;
foreach($counts AS $value => $count){
//Check one possible value, starting with the ones that appear the least amount of times
$key = null;
$scoreMin = null;
//Search each row with the value in it. Pick the row which has the lowest amount of other options
foreach($array AS $array_key => $array_options){
if(is_array($array_options)){
if(in_array($value,$array_options)){
//Get score
$score = 0;
$score = count($array_options)-1;
if($scoreMin === null OR ($score < $scoreMin)){
//Store row with lowest amount of other options
$scoreMin = $score;
$key = $array_key;
}
}
}
}
if($key !== null){
//Store that we changed something while running this function
$didChange = true;
//Change to count array. This holds how many times each value appears.
foreach($array[$key] AS $delValue){
$counts[$delValue]--;
}
//Remove chosen value from other arrays
foreach($array AS $rowKey => $options){
if(is_array($options)){
if(in_array($value,$options)){
unset($array[$rowKey][array_search($value,$options)]);
}
}
}
//Set value
$array[$key] = $value;
}
}
//validate, check if every row is an integer
$success = true;
foreach($array AS $row){
if(is_array($row)){
$success = false;
break;
}
}
if(!$success AND $didChange){
//Not done, but we made changes this run so lets try again
$array = pickUnique($array);
}elseif(!$success){
//Not done and nothing happened this function run, give up.
return null;
}else{
//Done
return $array;
}
}
My main problem is is that i have no way to verify if this is correct. Next to that i also am quite sure this problem has been solved a lot of times, but i cannot seem to find it. The only way i can verificate this (as far as i know) is by running the code a lot of times for random arrays and stopping when it encounters an insolvable array. Then i check that manually. So far the results are good, but this way of verication is ofcourse not correct.
I hope somebody can help me, either with the solution, the name of the problem or the verification method.

php recursive search and count of a value in json

I have a json feed with 6 objects all which have objects inside of them. I have an ID of something I am trying to search and count in another object.
if (isset($_GET['steamusr'])) {
$user = $_GET['steamusr'];
$myinv = 'http://steamcommunity.com/id/'.$user.'/inventory/json/295110/1/';
$content2 = file_get_contents($myinv);
$json2 = json_decode($content2, true);
$imgurlbase = 'http://steamcommunity-a.akamaihd.net/economy/image/';
foreach($json2['rgDescriptions'] as $i){
$item = $i['market_name'];
$icon = $i['icon_url'];
$fetchdata = 'http://steamcommunity.com/market/priceoverview/?appid=295110&currency=1&market_hash_name=' . urlencode($item);
$grab = file_get_contents($fetchdata);
$id = json_decode($grab, true);
$itemid = $i['classid'];
foreach($json2->rgInventory as $i2){
if($i2->$itemid == $itemid){
$ci = 0;
$count = $ci++ ;
}
}
All the data comes from rgDescriptions first, then rgInventory has the number of objects to count within it. The item ID comes from $itemid which I then need to search rgInventory for and then count the amount of matching id's in there from the set value $itemid.
My biggest issue is rgInventory has unique objects so I am trying to do a recursive/wildcard search of matching classid's.
The json structure can be found here: http://www.jsoneditoronline.org/?url=http://steamcommunity.com/id/fuigus/inventory/json/295110/1/
I think your code is correct in essence but you're not comparing the right things.
$json = json_decode($content2);
foreach ($json["rgDescriptions"] as $item) {
$num = 0;
foreach ($json["rgInventory"] as $inventory_entry) {
if ($inventory_entry["classid"] === $item["classid"]) {
$num += 1;
}
}
// do something with $num
var_dump($item["classid"] . ": " . $num);
}
The line:
if($i2->$itemid == $itemid){
Is bad, $i2->$itemid resolves to $i2->1107865473 which doesn't exist. I think you intended $i2->classid.
Error like this happen because you're using meaningless, abstract variable names. $i, $i2 and $content2, these are meaningless. You're also mixing the terms itemid and classid, it's easy to get confused.
Also, you're mixing bracket notation and object notation. Pick one and stick to it.

2 foreach loop, repeating results

Basically iv getting a list or orders, then a list of items associated with that user.
This is my code
$collection_array = array();
$collection_items_array = array();
foreach($getCollections as $k => $collection){
$collection_array['CustomerAccountID'] = $collection['collection_account_id'];
$collection_array['TotalCount'] = $collection['totalCount'];
// Get order items
$get_order_items = $Collection->getItems($collection['collection_account_id']);
foreach($get_order_items as $i => $items){
$collection_items_array['OrderID'] = $items['order_id'];
$collection_items_array['OrderItemID'] = $items['item_id'];
$cia[] = $collection_items_array;
}
$collection_array['CollectionItems'] = $cia;
$ca[] = $collection_array;
}
but when i echo this out, its showing all the correct results for the results but then it shows the seconds results + the results...

Loop through an array to create an SQL Query

I have an array like the following:
tod_house
tod_bung
tod_flat
tod_barnc
tod_farm
tod_small
tod_build
tod_devland
tod_farmland
If any of these have a value, I want to add it to an SQL query, if it doesnt, I ignore it.
Further, if one has a value it needs to be added as an AND and any subsequent ones need to be an OR (but there is no way of telling which is going to be the first to have a value!)
Ive used the following snippet to check on the first value and append the query as needed, but I dont want to copy-and-paste this 9 times; one for each of the items in the array.
$i = 0;
if (isset($_GET['tod_house'])){
if ($i == 0){
$i=1;
$query .= " AND ";
} else {
$query .= " OR ";
}
$query .= "tod_house = 1";
}
Is there a way to loop through the array changing the names so I only have to use this code once (please note that $_GET['tod_house'] on the first line and tod_house on the last line are not the same thing! - the first is the name of the checkbox that passes the value, and the second one is just a string to add to the query)
Solution
The answer is based heavily upon the accepted answer, but I will show exactly what worked in case anyone else stumbles across this question....
I didnt want the answer to be as suggested:
tod_bung = 1 AND (tod_barnc = 1 OR tod_small = 1)
rather I wanted it like:
AND (tod_bung = 1 OR tod_barnc = 1 OR tod_small = 1)
so it could be appended to an existing query. Therefore his answer has been altered to the following:
$qOR = array();
foreach ($list as $var) {
if (isset($_GET[$var])) {
$qOR[] = "$var = 1";
}
}
$qOR = implode(' OR ', $qOR);
$query .= " AND (" .$qOR . ")";
IE there is no need for two different arrays - just loop through as he suggests, if the value is set add it to the new qOR array, then implode with OR statements, surround with parenthesis, and append to the original query.
The only slight issue with this is that if only one item is set, the query looks like:
AND (tod_bung = 1)
There are parenthesis but no OR statements inside. Strictly speaking they arent needed, but im sure it wont alter the workings of it so no worries!!
$list = array('tod_house', 'tod_bung', 'tod_flat', 'tod_barnc', 'tod_farm', 'tod_small', 'tod_build', 'tod_devland', 'tod_farmland');
$qOR = array();
$qAND = array();
foreach ($list as $var) {
if (isset($_GET[$var])) {
if (!empty($qAND)) {
$qOR[] = "$var = 1";
} else {
$qAND[] = "$var = 1";
}
$values[] = $_GET[$var];
}
}
$qOR = implode(' OR ', $qOR);
if ($qOR != '') {
$qOR = '(' . $qOR . ')';
}
$qAND[] = $qOR;
$qAND = implode(' AND ', $qAND);
echo $qAND;
This will output something like tod_bung = 1 AND (tod_barnc = 1 OR tod_small = 1)
As the parameter passed to $_GET is a string, you should build an array of strings containing all the keys above, iterating it and passing the values like if (isset($_GET[$key])) { ...
You could then even take the key for appending to the SQL string.
Their are a lot of ways out their
$list = array('tod_house', 'tod_bung', 'tod_flat', 'tod_barnc', 'tod_farm', 'tod_small', 'tod_build', 'tod_devland', 'tod_farmland');
if($_GET){
$query = "";
foreach ($_GET as $key=>$value){
$query .= (! $query) ? " AND ":" OR ";
if(in_array($key,$list) && $value){
$query .= $key." = '".$value."'";
}
}
}
Sure you have to take care about XSS and SQL injection
If the array elements are tested on the same column you should use IN (...) rather than :
AND ( ... OR ... OR ... )
If the values are 1 or 0 this should do it :
// If you need to get the values.
$values = $_GET;
$tod = array();
foreach($values as $key => $value) {
// if you only want the ones with a key like 'tod_'
// otherwise remove if statement
if(strpos($key, 'tod_') !== FALSE) {
$tod[$key] = $value;
}
}
// If you already have the values.
$tod = array(
'tod_house' => 1,
'tod_bung' => 0,
'tod_flat' => 1,
'tod_barnc' => 0
);
// remove all array elements with a value of 0.
if(($key = array_search(0, $tod)) !== FALSE) {
unset($tod[$key]);
}
// discard values (only keep keys).
$tod = array_keys($tod);
// build query which returns : AND column IN ('tod_house','tod_flat')
$query = "AND column IN ('" . implode("','", $tod) . "')";

Categories