문제

I have Steam API working and functional but i want to count how many times an item is in the array so i can print how many items i have in stock.

I'm using this for Team Fortress 2 Items

This is the URL i use. I took out my API key and steam ID http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=APIKey&SteamID=Steam_ID&format=json

Its output is:

{
"result": {
    "status": 1,
    "num_backpack_slots": 300,
    "items": [
        {
            "id": 1264649944,
            "original_id": 1264649944,
            "defindex": 267,
            "level": 4,
            "quality": 5,
            "inventory": 2147483948,
            "quantity": 1,
            "origin": 1,
            "flag_cannot_trade": true
        },

But there are more items then just that one.

I want to know how to count the number of items with a specific defindex and print it.

EDIT:

<?php
$link = file_get_contents('http://api.steampowered.com/IEconItems_440/GetPlayer Items/v0001/?key=&SteamID=&format=json');
$myarray = json_decode($link, true);

print $myarray['result']['items'][0]['id'];
?>
도움이 되었습니까?

해결책

Use PHP's count:

<?php
$link = file_get_contents('http://api.steampowered.com/IEconItems_440/GetPlayer Items/v0001/?key=&SteamID=&format=json');
$myarray = json_decode($link, true);

echo count($myarray['result']['items']);
?>

EDIT: To count ones with a specific property you'll have to loop through all of them and increment a variable:

<?php
$link = file_get_contents('http://api.steampowered.com/IEconItems_440/GetPlayer Items/v0001/?key=&SteamID=&format=json');
$myarray = json_decode($link, true);

$count = 0;
foreach($myarray['result']['items'] as $item){
    if($item['defindex'] == 267){//or whatever you're looking for
        $count++;
    }
}
echo $count;
?>

다른 팁

You need to loop through your items array. If you are looking for a specific defindex you will just tally the number of times you see that specific value.

$total = 0;
foreach ($myarray->result->items as $item)
{
    if ($item->defindex == 5000)    // Scrap metal
    {
       $total++;
    }
}

If you are looking to tally each type of item, you will want to do something like:

$inv_array = array();
foreach ($myarray->result->items as $item)
{
    if (array_key_exists($item->defindex,$inv_array))
    {
        $inv_array[$item->defindex]++;
    }
    else
    {
        $inv_array[$item->defindex] = 1;
    }
}

var_dump($inv_array);

This will contain an array with a count of each unique defindex

The mistake you have in your code above is that you are looking at id. This is unique for every item in the TF2 economy AND changes with each new owner, and each new tool applied to the item.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top