Remove lines with empty values from multidimensional-array in php

后端 未结 5 1427
忘了有多久
忘了有多久 2021-01-21 23:50

How do you remove the lines that have empty elements from a multidimensional-array in PHP?

For instance, from:

1: a, b, c, d
2: d, _, b, a
3: a, b, _, _
         


        
相关标签:
5条回答
  • 2021-01-22 00:16

    Use this code:

    $source = array(
        array('a', 'b', 'c', 'd'),
        array('d', '_', 'b', 'a'),
        array('a', 'b', '_', '_'),
        array('d', 'c', 'b', 'a'),
        array('_', 'b', 'c', 'd'),
        array('d', 'c', 'b', 'a'),
    );
    
    $sourceCount = count($source);
    
    for($i=0; $i<$sourceCount; $i++)
    {
      if(in_array("_", $source[$i])) unset($source[$i]);
    }
    

    See: http://ideone.com/Vfd6Z

    0 讨论(0)
  • 2021-01-22 00:18
    $arr = array(... your multi dimension array here ...);
    foreach($arr as $idx => $row) {
        if (preg_grep('/^$/', $row)) {
            unset($arr[$idx]);
        }
    }
    
    0 讨论(0)
  • 2021-01-22 00:23

    Loop through the multidimensional array and check to see if the array at position i contains any empty elements. If it does, call unset($arr[i]) to remove it.

    for($i=0,$size=sizeof($arr); $i < $size; $i++) {
        if( in_array( "", $arr[$i] ) )
            unset( $arr[$i] );
    }
    
    0 讨论(0)
  • 2021-01-22 00:27

    Try this:

    Note: $arr is your array.

    foreach ( $arr as $key => $line ) {
    
        foreach ( $line as $item ) {
    
            if ( empty( $item ) ) {
    
                unset( $arr[$key] );
                break;
            }
    
        }
    
    }
    

    Cheers

    0 讨论(0)
  • 2021-01-22 00:36

    I would iterate through a foreach loop myself something like:

    <?php
        // Let's call our multidimensional array $md_array for this
    
        foreach ($md_array as $key => $array)
        {
            $empty_flag = false;
    
            foreach ($array as $key => $val)
            {
                if ($val == '')
                {
                    $empty_flag = true;
                }
            }
    
            if ($empty_flag == true)
            {
                unset($md_array[$key]);
            }
        }
    ?>
    

    There's almost definitely a more efficient way of doing this so anyone else who has a better solution feel free to let me and Alex know.

    0 讨论(0)
提交回复
热议问题