尝试对postcount上的foreach循环结果进行排序

时间:2019-06-26 17:11:58

标签: php arrays sorting foreach

试图按照从Invision Powerboard API(论坛软件)获得的帖子数对排名最高的海报进行排序。无法弄清楚如何对我的foreach循环的回声进行排序。

$curl = curl_init( $communityUrl . '/core/members/' );
curl_setopt_array( $curl, array(
    CURLOPT_RETURNTRANSFER  => TRUE,
    CURLOPT_HTTPAUTH    => CURLAUTH_BASIC,
    CURLOPT_USERPWD     => "{$apiKey}:"
    ) );
$response = curl_exec( $curl );
$data = json_decode($response, true);
$count = 0;
foreach($data as $member) {     
    if (is_array($member)) {
        foreach($member as $name) { 
            if($count > 4) 
                return;
            echo '<p class="top-member-p"><a href="'.$name['profileUrl'].'">'.ucfirst($name['name']).'</a> has '.$name['posts'] . ' posts</p>';
            $count++;
        }
    }
}

我希望将结果按其帖子数进行排序,如下所示:

"Swaghetti has 34 posts"<br>
"Josh has 15 posts"<br>
"Test has 3 posts"<br>
"Testuser2 has 0 posts"

但是它是这样的:

"Swaghetti has 34 posts"<br>
"Testuser2 has 0 posts"<br>
"Test has 3 posts"<br>
"Josh has 15 posts"

1 个答案:

答案 0 :(得分:4)

如果您没有其他选择来检索排序的数据,则可以自己使用usort()来完成,该操作由您自己的函数进行排序。与其他posts值进行比较,并将它们相应地放置在数组中(如果应将其向上移动,则返回1;如果应将其向下移动,则返回-1)。

我还添加了array_slice(),因为您似乎只想要前4个元素(这样一来,您只需获取这些元素,而无需计数器)。

// Test-data, I guessed my way to your format to match the output from what you had in the question
$data = [
    [['name' => 'Testuser2', 'posts' => 0, 'profileUrl' => 'swag']],
    [['name' => 'Josh', 'posts' => 15, 'profileUrl' => 'swag']],
    [['name' => 'Test', 'posts' => 3, 'profileUrl' => 'swag']],
    [['name' => 'Swaghetti', 'posts' => 34, 'profileUrl' => 'swag']],
];
// $data = json_decode($response, true);

usort($data, function($a, $b) {
    $a = array_column($a[0], 'posts');
    $b = array_column($b[0], 'posts');
    return ($a < $b) ? -1 : 1;
});

$slieced = array_slice($data, 0, 4);
foreach($slieced as $member) {
    if (is_array($member)) {
        foreach($member as $name) {
            echo '<p class="top-member-p">
                      <a href="'.$name['profileUrl'].'">'.ucfirst($name['name']).'</a> 
                      has '.$name['posts'] . ' posts
                  </p>'."\n";
        }
    }
}