-1

I have a question about php and json. Im running this php in foreach loop. But when i get all the tank_id from the json file. I get results like

8011819314145

I want it to display like: Tank ID: 801 Tank ID: 18193 Tank ID: 14145

What i'm doing wrong? Help me thank you.

Here is my php file:

<?php
    $json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
    $json_tank = json_decode($json, TRUE);
    foreach ($json_tank['521997295'] as $tank_id) {
        echo $tank_id['tank_id'];
    }
?>
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • foreach ($array as $key => $value) dublicate of http://stackoverflow.com/questions/1834703/php-foreach-loop-key-value and many more. Lol also you can put "Tank ID:" as a static text like @Rajdeep Paul properly points out – Velimir Tchatchevsky Jun 14 '16 at 14:53
  • 4
    Instead of `echo $tank_id['tank_id'];` do this, `echo "Tank ID:" . $tank_id['tank_id'] . "
    ";`
    – Rajdeep Paul Jun 14 '16 at 14:53
  • if i use this json url in loop is this right? example: `$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295&tank_id=" . $tank_id['tank_id']);` – Temuulen Optimistic Jun 14 '16 at 15:00
  • 1
    You don't have to change any url, just change the `echo` statement. – Rajdeep Paul Jun 14 '16 at 15:03

3 Answers3

2

In a foreach you can get both the key and the value. Take a look at the following pseudo-code

foreach ($array as $key => $value) {
    echo $key.': '.$value.'<br />';
}
Peter
  • 8,776
  • 6
  • 62
  • 95
1
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
echo('<pre>');
//print_r($json_tank);
foreach ($json_tank['data']['521997295'] as $tank_id) {
echo "Tank ID: " . $tank_id['tank_id'] . '<br/>';
}
ghkhan
  • 36
  • 4
0

You just need to format output as you want.

<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo 'Tank ID: '.$tank_id['tank_id'].' ';
}
?>
Branimir Đurek
  • 632
  • 5
  • 13