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