doulang2311 2016-02-26 16:12
浏览 125
已采纳

如果值不为空,则在foreach循环中对数组进行排序

I have this foreach loop and i was wondering if there could be a way to sort the array accurding to a value if it's not empty to be at top and the rest goes down. here what I have done so far:

foreach ((array)$accounts as $v=>$k){
        if(!empty($k)) {
                echo $v;
                echo "</br>";
                echo $k;
                echo "</br>";
        } else {
            echo $v;
            echo "</br>";
        }
    }

Note: $k returns either a string or it's just empty not NULL

The ouput is something like:

k1
v1
k2
k3
v3

As you can see k2 has no value. i want it to be at the bottom as it doesn't have a value.

Outputing the array directly with print_r($accounts, TRUE):

Array
(
    [TwitterSecKey] => Twitter Sec Key
    [GoogleSecKey] => 
    [InstagramSecKey] => Instagram Sec Key
    [FacebookSecKey] => 
)

As you can see Google and Facebook don't have values. so i want them to be at the bottom.

  • 写回答

3条回答 默认 最新

  • doujiexin1136 2016-02-26 17:22
    关注

    Thank you for finally providing your array structure.

    Based on your requirement of:

    sort the array accurding to a value if it's not empty to be at top and the rest goes down

    There is no need for complicated sorting algorithms with uasort(), please try this:

    <?php
    
    $accounts= array(
        'TwitterSecKey'=>'Twitter Sec Key',
        'GoogleSecKey'=>null,
        'InstagramSecKey'=>'Instagram Sec Key',
        'FacebookSecKey'=>null
    );
    
    echo '<pre>'.print_r($accounts, TRUE).'</pre>';
    
    arsort($accounts); // secret sauce
    
    echo '<pre>'.print_r($accounts, TRUE).'</pre>';
    

    http://php.net/manual/en/array.sorting.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?