Remove empty array elements

前端 未结 27 3398
半阙折子戏
半阙折子戏 2020-11-21 23:17

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

foreach($linksArray as $link)         


        
27条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 23:56

    Remove empty array elements

    function removeEmptyElements(&$element)
    {
        if (is_array($element)) {
            if ($key = key($element)) {
                $element[$key] = array_filter($element);
            }
    
            if (count($element) != count($element, COUNT_RECURSIVE)) {
                $element = array_filter(current($element), __FUNCTION__);
            }
    
            return $element;
        } else {
            return empty($element) ? false : $element;
        }
    }
    
    $data = array(
        'horarios' => array(),
        'grupos' => array(
            '1A' => array(
                'Juan' => array(
                    'calificaciones' => array(
                        'Matematicas' => 8,
                        'Español' => 5,
                        'Ingles' => 9,
                    ),
                    'asistencias' => array(
                        'enero' => 20,
                        'febrero' => 10,
                        'marzo' => '',
                    )
                ),
                'Damian' => array(
                    'calificaciones' => array(
                        'Matematicas' => 10,
                        'Español' => '',
                        'Ingles' => 9,
                    ),
                    'asistencias' => array(
                        'enero' => 20,
                        'febrero' => '',
                        'marzo' => 5,
                    )
                ),
            ),
            '1B' => array(
                'Mariana' => array(
                    'calificaciones' => array(
                        'Matematicas' => null,
                        'Español' => 7,
                        'Ingles' => 9,
                    ),
                    'asistencias' => array(
                        'enero' => null,
                        'febrero' => 5,
                        'marzo' => 5,
                    )
                ),
            ),
        )
    );
    
    $data = array_filter($data, 'removeEmptyElements');
    var_dump($data);
    

    ¡it works!

提交回复
热议问题