Change value of an array when null

2

I have a WebService in PHP that returns me a JSON with values from a mySQL database.

I need an Array, whenever there is a null value (when = null ), is changed to white ( = "" ).

I'm doing it this way, but without success.

<?php

header("Content-Type: application/json; charset=utf-8;");

include('connectdb.php');

$something = $_GET['cod'];
$sqlcode = mysql_query("Select descricao, cliente, local from terminal_cartao Where     descricao='$something'");
$sqlcode2 = mysql_query("Select descricao, cliente, local from terminal_cartao");

$jsonObj= array();

if($something == 'all')
{

while($result=mysql_fetch_object($sqlcode2))
{
$jsonObj[] = $result;
}

}

else{
while($result=mysql_fetch_object($sqlcode))
{
$jsonObj[] = $result;
}
}

foreach ($jsonObj as $key => $value) {
if ($value === null) {
    $jsonObj[$key] = ""; 
}
}

$final_res =json_encode($jsonObj);
echo $final_res;
exit;
    
asked by anonymous 04.11.2014 / 10:44

3 answers

3

Iterate through the array by checking and changing values:

foreach ($jsonObj as $k1 => $row) {
    foreach ($row as $k2 => $value) {
        if ($value === null) {
            $jsonObj[$k1]->$k2 = "";
        }
    }
} 
    
04.11.2014 / 10:52
5

I'll leave an alternative not only more efficient (nested loops are bad) but flexible enough to work with arrays of infinite dimensions:

function modify( $param ) {

    if( is_array( $param ) ) {
        return array_map( __FUNCTION__, $param );
    }

    if( $param === NULL ) {
        $param = '';
    }

    return $param;
}

If you do not know, array_map () applies a function to each element of an array. For each array that the current invocation finds, the function will be called again, again and again, recursively, behind the scenes.

When there are no more arrays to recurs, $ param is no longer an array and the function starts working, in this case, replacing the value and type NULL with an empty string.

Et voilà

    
04.11.2014 / 12:08
4

Another alternative is to apply a conditional in the SQL query. So there would be no need to change anything in PHP.

scope

IF(col_name IS NULL,"",col_name) AS col_name

Practical example using part of your code

$sqlcode = mysql_query("SELECT descricao, IF(cliente IS NULL,"",cliente) AS cliente, IF(local IS NULL,"",local) AS local from terminal_cartao WHERE descricao='$something'");

* In the working example, I will disregard the "description" column because of its use in the WHERE condition.

    
05.11.2014 / 16:19