php recursive search and count of a value in json - php

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.

Related

Counting the quantity by using the Steam Api

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.

extracting values from Mysql query

i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....

array/other data structure to store data in 2 dimention

Here First of all I fetched all tags from database. (tags are string like marketting,jobs etc).
$POS is array of POS(parts of speech words). For each words in this array, for given tag, I am calculating probability using writtten equation.
As it is appearing, two nested loops are there. To make decision, I need highest value from array $prob and tag belonging to that value.
Here in this code I will get all values in array $prob and from that I can get highest value, but how can I persist tag value too? is there any other data strcture in PHP to manage this short of scenario?
$selectTag = mysqli_query($con,"SELECT tag from koove_tag");
$prob = array();
$i=0;
while ($row1 = #mysqli_fetch_array($selectTag))
{
foreach($POS as $p)
{
//Calculate total pos for given tag
$selectPOS = mysqli_query($con,"SELECT * from koove_post where tag = '".$row1[tag]."'");
while ($row2 = #mysqli_fetch_array($selectTag))
{
$totalPOSs.=$row2[pos].",";
}
$totalPOS_count = str_word_count($totalPOSs);
//calculate how many times particular 'pos' appears for given tag
$selectPOS = mysqli_query($con,"SELECT * from koove_post where tag = '".$row1[tag]."'");
while ($row3 = #mysqli_fetch_array($selectTag))
{
$POSs.=$row3[pos].",";
}
$pos_Count = echo substr_count($string, $p);
//calculate distinct POS in all POSs for all tags
$selectPOS = mysqli_query($con,"SELECT pos from koove_post");
while ($row4 = #mysqli_fetch_array($selectTag))
{
$POSs.=$row4[pos].",";
}
$distinct_pos_Count = echo substr_count($string, $p);
$prob[$i] = ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count);
$i++;
}
}
There are large numbers(thousands) of posts, if is there any better approach to faster the processing that also welcome.
Certainly. Use the stdClass() object to hold the values that you need. Then write method to sort them. For example:
$prbo[$i] = new stdClass();
$prob[$i]->value = ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count);
$prob[$i]->tag = $row1[tag];
After you build that array, then write a custom sort function.
http://www.php.net/manual/en/array.sorting.php
1.You can use join query that will eliminate one of cycles.
2.You can get highest value with end(array) , or custom sort function.

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) . "')";

PHP Order in alphabetical order

I'm trying to make a simple alphabetical list to order items in my database. The thing I can't figure out is how to actually list it.
I would like it to be the same format as you have on miniclip.com
Here's an image
I looked around, but couldnt find an answer really.
(I would like it to finish even at the end of each vertical column, except the last one for sure)
Any help would be welcome!
In MySQL:
SELECT * FROM table ORDER BY name ASC
In PHP:
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
Assuming that your result set already is sorted by using the ORDER BY clause, to group the results by their first character you just need to remember the first character of the previous entry and print out the first character of the current entry if they are different. So:
$prevLabel = null;
while ($row = mysql_fetch_assoc($result)) {
$currLabel = strtoupper(substr($row['name'], 0, 1));
if ($currLabel !== $prevLabel) {
echo $currLabel;
$prevLabel = $currLabel;
}
echo $row['name'];
}
This will print the first character as a label for each group that’s members have the same first character.
He doesn't seem to have an issue with the storting, but doing the column format and headers for each new letter.
Suppose $arr contains your alphabetically sorted list with numeric keys. each element has indexes 'name' and 'link'. This should be pretty safe assumption for data from a SQL query.
$firstLetter = -1;
$desiredColumns = 4; //you can change this!
$columnCount = (count($arr)+27)/$desiredColumns+1;
echo "<table><tr><td>";
foreach($arr as $key => $cur)
{
if ($key != 0 && $key % desiredColumns == 0) echo "</td><td>";
if ($cur['name'][0] !== $firstLetter)
{
echo "<strong>$firstLetter</strong> <br />"; $firstLetter = $cur['name'][0];
}
echo "".$cur['name']."<br />";
}
echo "</td><tr></table>";
You'll have to treat numbers as a special case, but this is the idea. If you are using a template engine there are obviously better ways of doing this, but I figure you would have mentioned that. This is a rough sketch, making pretty HTML isn't my thing.
--Query-- get table into $arr. I can't see your tables obviously, Im making assumptions if names nad stuff so you'll need to verify or change them
$sql = "SELECT * FROM table T ORDER BY name";
$conn = //you should have this
$res = mysql_query($sql, $conn);
$arr = array();
while($row = mysql_fetch_assc($res)
$arr[] = $row;
// start above code here. This isn't safe for empty query responses or other error but it works
I presume you're using MySQL (or another SQL) database, in which case you should simply retrieve the data in the required order using a SORT BY clause on the lookup SELECT. (Sorting this PHP is trivial via the sort function, but it makes sense to get the database to do this - that's pretty much what it's for.)
In terms of balancing the output of each of the columns, you could get a COUNT of the required rows in your database (or simply use the count of the resulting PHP array of data) and use this to ensure that the output is balanced.
As a final thought, if this is going to be output on a per-page basis, I'd highly recommend generating it into a static file when the structure changes and simply including this static file as a part of the output - generating this on the fly is needlessly resource inefficient.
The mysql option mentioned above is definitely the best bet. If the data comes out of the DM in order, that's the simplest way to go.
Your next option might be to look at the
asort and ksort functions in PHP to find the exact one you're looking for.
http://www.php.net/manual/en/array.sorting.php
How are you pulling the data?
<?php
$result = mysql_query("SELECT titles FROM gamelist ORDER BY title ASC");
while ($row = mysql_fetch_assoc($result)) {
echo "{$result['title']}<br/>";
}
?>
There are two ways to do it.
You could use your database and use the 'order' clause to pull them by a specific field alphabetically.
You could also use either a key sort or value sort on a PHP array.
The PHP functions are sort($array) and ksort($array).
http://php.net/manual/en/function.sort.php
http://php.net/manual/en/function.ksort.php
<?php
$list = $your_list_array_from_database
//if you need info on how to do this, just let me know
sort($list);
foreach($list as $item) {
echo $item;
}
?>
I found this post and had the same problem. I used the code below to output a list by category name with a header equal to the first letter. In my database table (category) I have name and category_letter. So, name = football and category_list = 'F'.
<section>
<?php
try {
$cats_sql = $dbo->prepare("SELECT name, category_list, FROM category WHERE category_list REGEXP '^[A-Z#]' GROUP BY category_list ASC");
$cats_sql->execute();
$results_cats = $cats_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_cats = $results_cats;
if(is_array($array_cats)) {
foreach($array_cats as $row_cats) {
$cat_var = $row_cats[category_list]; // Each Category list title
?>
<aside>
<h1><a name=""><? echo $cat_var ?></a></h1>
<?php
try {
$search_sql = $dbo->prepare("SELECT name, category_list FROM category WHERE category_list=:cat_var ORDER BY name ASC"); // Pulling a list of names for the category list
$search_sql->bindParam(":cat_var",$cat_var,PDO::PARAM_STR);
$search_sql->execute();
$results_search = $search_sql->fetchAll();
} catch(PDOException $e) {
include('basehttp/error');
}
$array_search = $results_search;
if(is_array($array_search)) { // Output list of names which match category
foreach($array_search as $row_search) {
?>
<h2><?php echo $row_search[name]; ?></h2>
<br class="clear">
<?php
}
}
?>
</aside>
<br class="clear">
<?php
}
}
?>
</section>
Its actually Simple....I did similar thing for my project once. I had to pull out all music albums name and categorize them in alphabetical order.
In my table, "album_name" is the column where names are stored.
$sql= "select * from album_table order by album_name ASC";
$temp_char= ""; // temporary variable, initially blank;
using while loop, iterate through records;
while($row= $rs->fetch_assoc())
{
$album_name= $row['album_name'];
$first_char_of_albm= $album_name[0]; // this will store first alphabet;
$first_char_of_albm= strtoupper($first_char_of_albm); // make uppercase or lower as per your needs
if($temp_char!=$first_char_of_albm)
{
echo $first_char_of_albm;
$temp_char= $first_char_of_albm; // update $temp_char variable
}
}
That's it....
I am posting my answer to this old question for 3 reasons:
You don't always get to write your queries to MySQL or another DBMS, as with a web service / API. None of the other answers address PHP sorting without query manipulation, while also addressing the vertical alphabetical sort
Sometimes you have to deal with associative arrays, and only a couple other answers deal with assoc. arrays. BTW, my answer will work for both associative and indexed arrays.
I didn't want an overly complex solution.
Actually, the solution I came up with was pretty simple--use multiple tags with style="float:left", inside of a giant table. While I was sceptical that having multiple tbody tags in a single table would pass HTML validation, it in fact did pass without errors.
Some things to note:
$numCols is your desired number of columns.
Since we are floating items, you may need to set the width and min-width of parent elements and/or add some <br style="clear: both" />, based on your situation.
for alternative sorting methods, see http://php.net/manual/en/array.sorting.php
Here's my full answer:
function sortVertically( $data = array() )
{
/* PREPARE data for printing */
ksort( $data ); // Sort array by key.
$numCols = 4; // Desired number of columns
$numCells = is_array($data) ? count($data) : 1 ;
$numRows = ceil($numCells / $numCols);
$extraCells = $numCells % $numCols; // Store num of tbody's with extra cell
$i = 0; // iterator
$cCell = 0; // num of Cells printed
$output = NULL; // initialize
/* START table printing */
$output .= '<div>';
$output .= '<table>';
foreach( $data as $key => $value )
{
if( $i % $numRows === 0 ) // Start a new tbody
{
if( $i !== 0 ) // Close prev tbody
{
$extraCells--;
if ($extraCells === 0 )
{
$numRows--; // No more tbody's with an extra cell
$extraCells--; // Avoid re-reducing numRows
}
$output .= '</tbody>';
}
$output .= '<tbody style="float: left;">';
$i = 0; // Reset iterator to 0
}
$output .= '<tr>';
$output .= '<th>'.$key.'</th>';
$output .= '<td>'.$value.'</td>';
$output .= '</tr>';
$cCell++; // increase cells printed count
if($cCell == $numCells){ // last cell, close tbody
$output .= '</tbody>';
}
$i++;
}
$output .= '</table>';
$output .= '</div>';
return $output;
}
I hope that this code will be useful to you all.

Categories