Home > Enterprise >  Echo all of the ids as one id and get lines from it in PHP
Echo all of the ids as one id and get lines from it in PHP

Time:02-18

I'm working on Roblox Friends API https://friends.roblox.com/v1/users/261/friends Im trying to echo all of the Ids as $ids and echo it out like this $ids[2], Which is the third ID

<?php
$id = "261";
$ch = file_get_contents('https://friends.roblox.com/v1/users/'.$id.'/friends');

$data = json_decode($ch);

foreach ($data->id as $ids){
    echo $ids[1];
}
?>

This code doesn't work. Seems I cannot find an solution anywhere. I want it to echo out the first id.

CodePudding user response:

You can use next piece of code:

<?php
$id = "261";
$ch = file_get_contents('https://friends.roblox.com/v1/users/'.$id.'/friends');

$data = json_decode($ch)->data;

foreach ($data as $d){
    echo $d->id . PHP_EOL;
}

Test PHP json_decode online

CodePudding user response:

You can try something like this

$ch = file_get_contents('https://friends.roblox.com/v1/users/261/friends');
//set to TRUE if you want to use the result as associative array
$data = json_decode($ch, true)['data'];
//simple loop over your data
foreach($data as $datum) {
    echo $datum['id'] . "<br>";
}
//or if you need to keep only the id of each item 
$ids = array_column($data, 'id');
foreach($ids as $id) {
    echo $id . "<br>";
}
  • Related