0

I have this array converted by json_decode collected from an api :

Array ( [Success] => 1 [Message] => [Data] => Array ( [0] => Array ( [TradePairId] => 1261 [Label] => $$$/BTC [AskPrice] => 3.1E-7 [BidPrice] => 3.0E-7 [Low] => 3.0E-7 [High] => 3.2E-7 [Volume] => 705593.52096319 [LastPrice] => 3.0E-7 [BuyVolume] => 25256894.050968 [SellVolume] => 18662564.012659 [Change] => 0 [Open] => 3.0E-7 [Close] => 3.0E-7 [BaseVolume] => 0.21205524 [BuyBaseVolume] => 1.29049546 [SellBaseVolume] => 25462.44174616 ) [1] => Array ( [TradePairId] => 1263 [Label] => $$$/DOGE [AskPrice] => 0.5899991 [BidPrice] => 0.46100022 [Low] => 0.46100044 [High] => 0.6 [Volume] => 16724.82996554 [LastPrice] => 0.49000028 [BuyVolume] => 44142637347.254 [SellVolume] => 431226.52315815 [Change] => -18.33 [Open] => 0.6 [Close] => 0.49000028 [BaseVolume] => 8561.99438073 [BuyBaseVolume] => 108392.69695843 [SellBaseVolume] => 8677417.2428937 )......

I need to display only Label and LastPrice.

I am trying with this :

<?php
$jsondata = file_get_contents('https://www.cryptopia.co.nz/api/GetMarkets');
$data = json_decode($jsondata, true);


foreach ($data['0']['Label'] as $key=>$val) {
    print_r($key);
}
//print_r($data);

?>

but could not succeed.

JYoThI
  • 11,977
  • 1
  • 11
  • 26
techansaari
  • 375
  • 1
  • 5
  • 20
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – user3942918 Aug 02 '17 at 03:50
  • One thing that is *unobvious* here is the `Message` element in the array posted at the top of this question is an *empty string*. – FKEinternet Aug 02 '17 at 04:24

3 Answers3

2

Find your solution below:

$jsondata = file_get_contents('https://www.cryptopia.co.nz/api/GetMarkets');
$data = json_decode($jsondata, true);


foreach ($data['Data'] as $key=>$val) {
    echo "Label=".$val['Label'];
    echo "<br>";
    echo "Last price=".$val['LastPrice'];
    echo "<br>";
}
Mansi Raja
  • 152
  • 1
  • 13
0

You need to loop the Data index in foreach

foreach ($data['Data'] as $key=>$val) {

      echo "label : ". $val['Label']."   price :".$val['LastPrice']."<br>";
}
JYoThI
  • 11,977
  • 1
  • 11
  • 26
0

You don't need to do foreach ($data['Data'] as $key=>$val), simply foreach ($data['Data'] as $val) will get the results you need since you're not using the $key anywhere:

$jsondata = file_get_contents('https://www.cryptopia.co.nz/api/GetMarkets');
$data = json_decode($jsondata, true);

foreach ($data['Data'] as $val)
{
    echo $val['Label'].' = '.$val['LastPrice'].'<br>';
}

Also, use single quotes for static strings so PHP doesn't have to parse them looking for variables or escape sequences.

FKEinternet
  • 1,050
  • 1
  • 11
  • 20