charlion78 Posted February 9, 2021 Share Posted February 9, 2021 Hello everyone. I'm a self learner that is very new to programming. I'm trying to print out the value of ["mid"] from a json_decode variable in the code shown below: I'm trying to use for each to access the value of "mid'. using foreach function. I know I'm not doing it the right way. please help me or show me an easy was to go around it. /////the json resopnd form the url is : {"terms":"http://www.xe.com/legal/dfs.php","privacy":"http://www.xe.com/privacy.php","from":"USD","amount":1.195,"timestamp":"2021-02-09T16:52:00Z","to":[{"quotecurrency":"NGN","mid":454.6559871014}]} ///////////////////////////////////////////////// <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $price){ echo $price['mid']; }; ?> Quote Link to comment https://forums.phpfreaks.com/topic/312115-how-to-echo-out-a-value-from-json-array/ Share on other sites More sharing options...
Solution Barand Posted February 9, 2021 Solution Share Posted February 9, 2021 (edited) If you echo '<pre>$json = ', print_r($json, 1), '</pre>'; you get $json = Array ( [terms] => http://www.xe.com/legal/dfs.php [privacy] => http://www.xe.com/privacy.php [from] => USD [amount] => 1.195 [timestamp] => 2021-02-09T16:52:00Z [to] => Array ( [0] => Array ( [quotecurrency] => NGN [mid] => 454.6559871014 ) ) ) Then follow the array keys to the value you want So you need echo $json['to'][0]['mid']; // --> 454.6559871014 [edit] Alternatively foreach ($json['to'] as $price) { printf('%s %0.2f<br>', $price['quotecurrency'], $price['mid'] ); // --> NGN 454.66 } Edited February 9, 2021 by Barand 1 Quote Link to comment https://forums.phpfreaks.com/topic/312115-how-to-echo-out-a-value-from-json-array/#findComment-1584337 Share on other sites More sharing options...
Strider64 Posted February 9, 2021 Share Posted February 9, 2021 (edited) Ooops read it wrong ..... please delete 😃 Edited February 9, 2021 by Strider64 Quote Link to comment https://forums.phpfreaks.com/topic/312115-how-to-echo-out-a-value-from-json-array/#findComment-1584339 Share on other sites More sharing options...
charlion78 Posted February 10, 2021 Author Share Posted February 10, 2021 Thanks alot @Barand. you answer helps me alot Quote Link to comment https://forums.phpfreaks.com/topic/312115-how-to-echo-out-a-value-from-json-array/#findComment-1584347 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.