【问题标题】:How to print following json data using foreach in php(coinmarket api)如何在php(coinmarket api)中使用foreach打印以下json数据
【发布时间】:2019-10-09 04:06:19
【问题描述】:

我正在尝试在 php 的 foreach 循环中打印以下 json 数据。谁能告诉我我该怎么做?我搜索了很多,但没有任何效果。 我从 coinmarket api 获取这些数据并使用以下方法打印此代码: 但未能分别获取每个值。

$curl = curl_init(); // Get cURL resource
    // Set cURL options
    curl_setopt_array($curl, array(
      CURLOPT_URL => $request,            // set the request URL
      CURLOPT_HTTPHEADER => $headers,     // set the headers 
      CURLOPT_RETURNTRANSFER => 1         // ask for raw response instead of bool
    ));
  $response = curl_exec($curl); // Send the request, save the response
    print_r(json_decode($response));

下面是我想在 foreach 循环中使用的代码:

stdClass Object ( [status] => stdClass Object ( [timestamp] => 2019-10-09T03:13:30.051Z [error_code] => 0 [error_message] => [elapsed] => 9 [credit_count] => 1 [notice] => ) [data] => stdClass Object ( [BTC] => stdClass Object ( [id] => 1 [name] => Bitcoin [symbol] => BTC [slug] => bitcoin [num_market_pairs] => 7935 [date_added] => 2013-04-28T00:00:00.000Z [tags] => Array ( [0] => mineable ) [max_supply] => 21000000 [circulating_supply] => 17981825 [total_supply] => 17981825 [platform] => [cmc_rank] => 1 [last_updated] => 2019-10-09T03:12:33.000Z [quote] => stdClass Object ( [USD] => stdClass Object ( [price] => 8195.0290967 [volume_24h] => 14981665979.667 [percent_change_1h] => -0.224992 [percent_change_24h] => -1.35388 [percent_change_7d] => -1.38135 [market_cap] => 147361579086.77 [last_updated] => 2019-10-09T03:12:33.000Z ) ) ) ) )

【问题讨论】:

    标签: php json api


    【解决方案1】:

    请格式化您的问题、代码和输出,使其变得可读。你还试过什么?您需要什么数据?

    要获取数据中检索到的所有硬币的名称列表,您可以使用以下代码:

    $response = json_decode($response);
    
    foreach ($response->data as $coin){ // assuming the data could contain multiple coins
        echo $coin->name;
        echo '<br>';
    }
    

    提示:如果您想在 HTML 页面中看到格式化的 print_r() 输出,您可以将它放在 PRE 标记之间。

    echo '<pre>';
    print_r($my_object);
    echo '</pre>';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 2021-02-11
      • 2016-01-14
      相关资源
      最近更新 更多