I have some PHP code that grabs data from JSON. The code retruns all the usernames, including the current username to display. My question is, how would I only allow it so that it only shows the recent usernames and not the current?
I am using the Minecraft API for this and the JSON code I am getting can be found here.
Note that
_scrunch
is the current username.
Here's my code that displays the names:
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
//do
// $input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
and to display it
<?php echo implode(', ', $names) ;?>
Any help would be great! Thanks!
In your loop, just check and exclude if it's the user's name:
foreach ($json as $name) {
$input = $name->name;
if ($input != _scrunch) {
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
//do
// $input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
}
If you're looking to remove the last element of the array, array_pop() should do the trick. Then your foreach loop will look over all the elements except the last one.
$array = [1, 2, 3]; // sample array
$last = array_pop($array); // remove last element of array and store it into a variable => $array = [1, 2]
// do stuff
foreach($array as $element) {
...
}
array_push($array, $last); // push the element to the back of the array => $array = [1, 2, 3]
Simply count the amount of data returned in the array through the count
function, and then rank each item within the foreach loop by doing $foo ++;
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$total = count($json); // This counts the amount of items returned
$rank = 0; // Declaring the rank for future use in the foreach loop
$names = array(); // Create a new array
foreach ($json as $name) {
$rank ++;
$input = $name->name;
if ($rank == $total){
// Do something if this is the last row
}
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
//do
// $input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}