计算数组中的项目数

时间:2016-01-31 17:22:44

标签: php arrays json

这是我的代码。 我试图通过steam API获得多少交易报价。 我可以得到一个数组,但我不知道如何计算这个数组中的项目数

<?php 
$json_url = "http://api.steampowered.com/IEconService/GetTradeOffers/v0001/?key=KEY&get_received_offers=1&active_only=1";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>' . print_r($data, true) . '</pre>';

如何获得[trade_offers_recived]的数量?目前有2个交易要约(0和1)

3 个答案:

答案 0 :(得分:1)

函数count甚至可以用于数组的子数组。

因此,如果你需要一个子数组中的元素数,这个元素位于键'trade_offers_recived'下面,而response依次位于键echo count($data['response']['trade_offers_received']); 下:

seq = "word1 defined as blah blahh blahhh word2 defined as hello helloo"

words_of_interest = []

list_of_words = seq.split(" ")
for i,word in enumerate(list_of_words):
    if word == "defined":
        words_of_interest.append(list_of_words[i-1])
print words_of_interest
#['word1', 'word2']

答案 1 :(得分:1)

如上所述链接,您的数组如下所示:

Array
(
    [response] => Array
        (
            [trade_offers_received] => Array
                (
                    [0] => Array
                    ...

所以你只需要对trade_offers_received键进行计数:

<?php
print count($data['response']['trade_offers_received']);

答案 2 :(得分:1)

您的$ data数组包含“响应”数组和这些“trade_offers_received”数组。所以试试这个:

$numtradeoffers = count($data['response']['trade_offers_received']);
相关问题