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条)

报告相同问题?