Sort PHP array by amount of viewers

Asked
Active3 hr before
Viewed126 times

9 Answers

array
90%

Im developing a custom script (right now, it is dirty). Basically it lists the stream info and links that are in my database. At the same time, it gets info from the twitch.tv API. And one of the info retrieved from the API is the amount of viewers. How do I sort the list by the amount of viewers, highest first? I tried using the sort function but I don't know how to use it in this case., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , possible duplicate of Sort Multi-dimensional Array by Value – Pitchinnate Mar 28 '14 at 18:30 ,Making statements based on opinion; back them up with references or personal experience.

Tested with provided json data and working:

<?php
    $con = mysqli_connect("localhost", "****", "****", '****');
    $result = mysqli_query($con,"SELECT * FROM streams");

    echo "<table border='1'>";
    echo "<tr>";
    echo "<th>Stream name</th>";
    echo "<th>status</th>";
    echo "<th>game</th>";
    echo "<th>viewers</th>";
    echo "</tr>";

    $data = array();
    while($row = mysqli_fetch_array($result)) {
        $json = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($row['channel']).'?client_id='.$clientId), true);
        if(!is_null($json->stream))
            $data[] = array(
                'display_name' => $json->stream->channel->display_name,
                'status' => $json->stream->channel->status,
                'game' => $json->stream->channel->game,
                'viewers' => $json->stream->viewers);
    }
    usort($data, function($a,$b) {return $a['viewers'] < $b['viewers'];});
    foreach($data as $item) {
        echo "<tr>";
        echo "<td>{$item['display_name']}</td>";
        echo "<td>{$item['status']}</td>";
        echo "<td>{$item['game']}</td>";
        echo "<td>{$item['viewers']}</td>";
        echo "</tr>";
    }
    echo "</table>";
 ?>
88%

This function performs sorting on the given array and arranges the array’s keys in ascending order using the compare function.,This is a guide to Sorting in PHP. Here we discuss how sorting is performed and different types of Sorting in PHP along with its examples. You may also look at the following articles to learn more-,The following example sorts the elements of the $people and $ages array.,This function performs sorting on the given array and arranges the array’s values in ascending order using the compare function.

Syntax:

sort(array);

sort(array);
load more v
72%

$inventory = array(

   array("type" => "fruit", "price" => 3.50),
   array("type" => "milk", "price" => 2.90),
   array("type" => "pork", "price" => 5.43),

);
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
load more v
65%

So also you can use the sort function on the numeric components of the array example is given below.,Array Sorting Functions,There are many functions that you can use to sort arrays in PHP. Some functions use to sort array keys while others can be used to sort arrays values. So, this means in PHP you can sort array in both directions either with keys or values. Below are the sorting arrays functions in PHP.,The above array returns the below data.

<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");

// Sorting and printing array
sort($colors);

print"<pre>";
print_r($colors);
print"</pre>";
?>
load more v
75%

I got my answer via the Drupal Slack, but reposting it here for anyone who might come across this later, since that's not publicly searchable. It was more of a PHP issue than anything Drupal-specific.,Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.,In a views_pre_render() hook, I calculate the points total for each row and place it into an array, $songAndPoints, that contains the song's nid and points total. The array is sorted so that the song with the highest points total comes first – therefore, the order of the nids in the array is the order in which I want my results to appear.,Continuing on, I figured out that switching it to an anonymous function was what I needed to pass $songAndPoints to the uasort() function, as follows, instead of separating it:

Within the uasort() callback, the $left and $right arguments are objects of the ResultRow class, with nid available from them, so switching $leftPos and $rightPos to $flipped[$left->nid] and $flipped[$right->nid], respectively, gets me access to the results' nids.

/**
 * Custom uasort() callback to sort view results by points totals.
 */
function MODULE_sort_by_points_total($left, $right) {
   $order = ['704', '712', '707', '713', '711', '709', '708', '883', '882', '715', '714', '710', '705'];

   $flipped = array_flip($order);
   $leftPos = $flipped[$left - > nid];
   $rightPos = $flipped[$right - > nid];
   return $leftPos >= $rightPos;
}
load more v
40%

If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. , SORT_REGULAR - compare items normally; the details are described in the comparison operators section ,rsort() - Sort an array in descending order,sort — Sort an array in ascending order

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
load more v
22%

Array Sort In PHP: Everything ...,usort():Array Sort In PHP ,This brings us to the final bit of this Array Sort In PHP article,All you Need to Know About Implements In Java

Using this method, by default the array is sorted in ascending order.

<pre>
<?php
$var_array = array(10,20,30,40);
sort($var_array);
print_r($var_array);
?>
</pre>
load more v
60%

The Arr::flatten method flattens a multi-dimensional array into a single level array:,The Arr::dot method flattens a multi-dimensional array into a single level array that uses "dot" notation to indicate depth:,The Arr::collapse method collapses an array of arrays into a single array:,The Arr::last method returns the last element of an array passing a given truth test:

The Arr::accessible method determines if the given value is array accessible:

use Illuminate\ Support\ Arr;
use Illuminate\ Support\ Collection;

$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);

// true

$isAccessible = Arr::accessible(new Collection);

// true

$isAccessible = Arr::accessible('abc');

// false

$isAccessible = Arr::accessible(new stdClass);

// false
load more v
48%

Last argument is PHP sort flag that could take the same values as the ones passed to PHP sort().,Third argument is direction. In case of sorting by a single key it could be either SORT_ASC or SORT_DESC. If sorting by multiple values you can sort each value differently by providing an array of sort direction.,If additional transformations are required or the way of getting value is complex, second argument could be specified as an anonymous function:,multisort method helps to sort an array of objects or nested arrays by one or several keys. For example,

Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite repetitive. You have to check if key exists with isset first, then if it does you're getting it, if not, providing default value:

class User {
   public $name = 'Alex';
}

$array = [
   'foo' => [
      'bar' => new User(),
   ]
];

$value = isset($array['foo']['bar'] - > name) ? $array['foo']['bar'] - > name : null;
load more v

Other "array-undefined" queries related to "Sort PHP array by amount of viewers"