Remove empty array elements

前端 未结 27 3496
半阙折子戏
半阙折子戏 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条回答
  • 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!

    0 讨论(0)
  • 2020-11-21 23:59

    If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:

    array_values(array_filter($array));
    

    Also see: PHP reindex array?

    0 讨论(0)
  • 2020-11-22 00:02
    $linksArray = array_filter($linksArray);
    

    "If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

    0 讨论(0)
  • 2020-11-22 00:02

    With these types of things, it's much better to be explicit about what you want and do not want.

    It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.

    Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.

    In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.

    Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop.

    <?php
    
    $xs = [0, 1, 2, 3, "0", "", false, null];
    
    $xs = array_filter($xs, function($x) {
        if ($x === null) { return false; }
        if ($x === false) { return false; }
        if ($x === "") { return false; }
        if ($x === "0") { return false; }
        return true;
    });
    
    $xs = array_values($xs); // reindex array   
    
    echo "<pre>";
    var_export($xs);
    

    Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.

    See this example and the inline comments for the output.

    <?php
    
    /**
     * @param string $valueToFilter
     *
     * @return \Closure A function that expects a 1d array and returns an array
     *                  filtered of values matching $valueToFilter.
     */
    function filterValue($valueToFilter)
    {
        return function($xs) use ($valueToFilter) {
            return array_filter($xs, function($x) use ($valueToFilter) {
                return $x !== $valueToFilter;
            });
        };
    }
    
    // partially applied functions that each expect a 1d array of values
    $filterNull = filterValue(null);
    $filterFalse = filterValue(false);
    $filterZeroString = filterValue("0");
    $filterEmptyString = filterValue("");
    
    $xs = [0, 1, 2, 3, null, false, "0", ""];
    
    $xs = $filterNull($xs);        //=> [0, 1, 2, 3, false, "0", ""]
    $xs = $filterFalse($xs);       //=> [0, 1, 2, 3, "0", ""]
    $xs = $filterZeroString($xs);  //=> [0, 1, 2, 3, ""]
    $xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]
    
    echo "<pre>";
    var_export($xs); //=> [0, 1, 2, 3]
    

    Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.

    <?php
    
    /**
     * Supply between 1..n functions each with an arity of 1 (that is, accepts
     * one and only one argument). Versions prior to php 5.6 do not have the
     * variadic operator `...` and as such require the use of `func_get_args()` to
     * obtain the comma-delimited list of expressions provided via the argument
     * list on function call.
     *
     * Example - Call the function `pipe()` like:
     *
     *   pipe ($addOne, $multiplyByTwo);
     *
     * @return closure
     */
    function pipe()
    {
        $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo]
        return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1
            return array_reduce( // chain the supplied `$arg` value through each function in the list of functions
                $functions, // an array of functions to reduce over the supplied `$arg` value
                function ($accumulator, $currFn) { // the reducer (a reducing function)
                    return $currFn($accumulator);
                },
                $initialAccumulator
            );
        };
    }
    
    /**
     * @param string $valueToFilter
     *
     * @return \Closure A function that expects a 1d array and returns an array
     *                  filtered of values matching $valueToFilter.
     */
    function filterValue($valueToFilter)
    {
        return function($xs) use ($valueToFilter) {
            return array_filter($xs, function($x) use ($valueToFilter) {
                return $x !== $valueToFilter;
            });
        };
    }
    
    $filterer = pipe(
        filterValue(null),
        filterValue(false),
        filterValue("0"),
        filterValue("")
    );
    
    $xs = [0, 1, 2, 3, null, false, "0", ""];
    $xs = $filterer($xs);
    
    echo "<pre>";
    var_export($xs); //=> [0, 1, 2, 3]
    
    0 讨论(0)
  • 2020-11-22 00:04
    function trim_array($Array)
    {
        foreach ($Array as $value) {
            if(trim($value) === '') {
                $index = array_search($value, $Array);
                unset($Array[$index]);
            }
        }
        return $Array;
    }
    
    0 讨论(0)
  • 2020-11-22 00:04

    try this ** **Example

    $or = array(
            'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
            'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
            'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
            'PersonalInformation.dob' => $this->request->data['User']['dob'],
            'User.email' => $this->request->data['User']['email'],
        );
    
    
    
     $or = array_filter($or);
    
        $condition = array(
            'User.role' => array('U', 'P'),
            'User.user_status' => array('active', 'lead', 'inactive'),
            'OR' => $or
        );
    
    0 讨论(0)
提交回复
热议问题