-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'];
    }
?>
4
  • foreach ($array as $key => $value) dublicate of 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 Commented Jun 14, 2016 at 14:53
  • 4
    Instead of echo $tank_id['tank_id']; do this, echo "Tank ID:" . $tank_id['tank_id'] . "<br />"; Commented Jun 14, 2016 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']); Commented Jun 14, 2016 at 15:00
  • 1
    You don't have to change any url, just change the echo statement. Commented Jun 14, 2016 at 15:03

3 Answers 3

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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

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/>';
}

Comments

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'].' ';
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.