How does one filter the response data null through the PHP development interface?

Source: Internet
Author: User
The response data may be a one-dimensional array or a two-dimensional array. How to filter null before json_encode? The response data may be a one-dimensional array or a two-dimensional array. How to filter null before json_encode?

Reply content:

The response data may be a one-dimensional array or a two-dimensional array. How to filter null before json_encode?

Array_filter can only remove null values of 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. By default, all "", null, and false can be filtered out.
If you only need to filter out null, 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 use array_filter.

Array_filter can only filter a group of arrays, but most of the arrays obtained from the database are two-dimensional. Therefore, you need to write a function yourself and implement it recursively.

The best way is to discuss it with the API developers. Do not return null and return ''better than it,

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

Speaking of array_filter upstairs, actuallyarray_filter($arr,'strlen')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.