【问题标题】:Trying to sort my result of foreach loop on postcount试图在 postcount 上对我的 foreach 循环结果进行排序
【发布时间】:2019-11-08 16:55:06
【问题描述】:

尝试根据从 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"

【问题讨论】:

    标签: php arrays sorting foreach


    【解决方案1】:

    如果您没有其他选项来检索已排序的数据,您可以自己进行 - 使用 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";
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 2015-06-05
      • 2020-01-27
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多