1

I'm just trying to display an API response as an Array, but something is wrong and I don't find it:

The API's answer:

{"status":"OK","minecrafts":[{"id":411,"ip":"2452453","name":"EdenCraft","port":23,"ram":512,"leaf_id":1522,"ftp_password":"1231235312","subscription_end":"2014-02-06T19:56:29.000Z"}]}

My PHP code:

<?php
$url = "http://api.edenservers.fr/minecraft?user_id=id&api_key=key";
$data = file_get_contents($url); // Opening the Query URL
$data = json_decode($data, true); // Decoding the obtained JSON data
if(count($data) > 0) {
    foreach($data as $rank => $donnees) {
        echo "<u>" . $rank ."</u> : ". $rank;
        echo "<br />";
    }
}
else {
    echo "Rien n'a &eacute;t&eacute; trou&eacute;.";
}
?>

And this is what's showed on my Dashboard:

status : status

minecrafts : minecrafts

Thanks for your help !

2 Answers 2

1

Try

foreach($data as $key=>$val){
  if(is_array($val)){
       foreach($val[0] as $key1=>$val1){
          echo "<u>" . $key1 ."</u> : ". $val1;
       } 
   }else{
           echo "<u>" . $key ."</u> : ". $val;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change:

echo "<u>" . $rank ."</u> : ". $rank

to:

echo "<u>" . $rank ."</u> : ". print_r( $donnees, TRUE )

Or the other way around if you want the values reversed. But the issue is with using $rank in both places.

1 Comment

Looks like it's a multi-dimensional array, so $donnees itself is still an array instead of a string in certain cases. The edit I made above should solve that, though you'll have to modify it (such as perhaps including a nested foreach() to loop through it) based on how you want the output formatted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.