doupa2871 2017-04-27 08:52 采纳率: 100%
浏览 67
已采纳

PHP:从数组中删除空值并向上移动值

I'm trying to create a function that shifts array values up a key if the previous key is empty and one after is set. E.g. this array:

array (size=4)
    'row1' => string 'row1' (length=4)
    'row2' => string '' (length=0)
    'row3' => string '' (length=0)
    'row4' => string 'row4' (length=4)

should become this after my function call:

array (size=4)
    'row1' => string 'row1' (length=4)
    'row2' => string 'row4' (length=4)
    'row3' => string '' (length=0)
    'row4' => string '' (length=0)

I do have a working function, however, it uses a lot of if statements and I'm 100% sure that it could be done more efficiently, any ideas on how to achieve efficiently?

Thanks

  • 写回答

4条回答 默认 最新

  • doubleyou1001 2017-04-27 09:11
    关注

    Lets try this with a big array, and hope this will help you out. The way of question is different but your question is same as

    1. Getting empty values at end.

    2. Non empty at starting without changing order

    3. Without changing keys order

    If you think about any array this result come to end.

    Try this code snippet here

    <?php
    
    $array=$tempArray=array(
        'row1' =>  'row1',
        'row2' =>  '' ,
        'row3' =>  '',
        'row6' =>  'row6' ,
        'row4' =>  'row4' ,
        'row5' =>  '',
        'row7' =>  'row7' ,
        'row8' =>  ''
    );
    $result=array();
    $tempArray=  array_values($tempArray);
    $tempArray=array_values(array_filter($tempArray));
    
    foreach(array_keys($array) as $key_key => $key)
    {
        if(!empty($tempArray[$key_key]))
        {
            $result[$key]=$tempArray[$key_key];   
        }
        else
        {
            $result[$key]="";
        }
    }
    print_r($result);
    

    Output:

    Array
    (
        [row1] => row1
        [row2] => row6
        [row3] => row4
        [row6] => row7
        [row4] => 
        [row5] => 
        [row7] => 
        [row8] => 
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

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