Home > Backend Development > PHP Tutorial > PHP开发接口响应数据null怎么过滤?

PHP开发接口响应数据null怎么过滤?

WBOY
Release: 2016-06-06 20:09:39
Original
1424 people have browsed it

响应的数据可能是一维的数组,也可能二维的数组,再json_encode之前,怎么过滤null?

回复内容:

响应的数据可能是一维的数组,也可能二维的数组,再json_encode之前,怎么过滤null?

array_filter是只能去除掉一维的数组的null

<code>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;
}</code>
Copy after login

有现成的函数,默认可以过滤掉所有 ""、null、false
如果单独只需要过滤掉null,那么类似如下代码写一个回调函数

<code>function delete_null($vo){
    if ($vo==null){
        return false;
    }
    return true;
}
print_r(array_filter(array("aaa","bbb",null,"ccc"),"delete_null"));</code>
Copy after login

直接array_filter就可以了吧

array_filter其实只能过滤一组数组,但是从数据库获取的多数是二维,所以这个还是要自己写一个函数,可以递归实现。

最好的办法是和开发API的兄弟商量一下,别返回null 返回''也比它强,

<code>$data= \str_replace(':null', ':""', json_encode($data));</code>
Copy after login

楼上说到array_filter,其实array_filter($arr,'strlen')这样过滤就可以,然后json_encode

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template