PHP Development Interface Response data null how to filter?

Source: Internet
Author: User
The response data may be one-dimensional arrays, or two-dimensional arrays, before json_encode, how to filter null?

Reply content:

The response data may be one-dimensional arrays, or two-dimensional arrays, before json_encode, how to filter null?

Array_filter is null to remove only one-dimensional arrays

function null_filter($arr){    foreach($arr as $key=>&$val) {        if(is_array($val)) {            $val = null_filter($val);        } else {            if($val === null){                unset($arr[$key]);            }        }    }    return $arr;}

There are ready-made functions that can filter out all ", NULL, FALSE by default
If you only need to filter out null, then write a callback function similar to the following code

function delete_null($vo){    if ($vo==null){        return false;    }    return true;}print_r(array_filter(array("aaa","bbb",null,"ccc"),"delete_null"));

Just array_filter it.

Array_filter actually can only filter a set of arrays, but most of the data obtained from the database is two-dimensional, so this is still to write a function, can be implemented recursively.

The best way is to discuss with the developer of the API, do not return null return ' is also stronger than it,

$data= \str_replace(':null', ':""', json_encode($data));

Upstairs talking about Array_filter, in fact, array_filter($arr,'strlen') this filter can be, and then Json_encode

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.