Exchange array value when null

Asked

Viewed 806 times

2

I have a Webservice in PHP that returns me a JSON with values from a mysql database.

I need that, in an Array, whenever there is a null value (when = null), be replaced by 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;

3 answers

5

I will leave an alternative not only more efficient (nested loops are bad) but also 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 don’t 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 recur, $stop 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à

4

Another alternative is to apply a condition in the SQL query. So there would be no need to modify 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 practical example, I disregarded the "Description" column due to its use in the WHERE condition.

3


Iterate through the array by checking and exchanging values:

foreach ($jsonObj as $k1 => $row) {
    foreach ($row as $k2 => $value) {
        if ($value === null) {
            $jsonObj[$k1]->$k2 = "";
        }
    }
} 
  • did not work, edited my answer and put the complete code. What may be wrong?

  • I edited the answer now for two-dimensional array.

  • Cannot use Object of type stdClass as array in $jsonObj[$k1][$k2] = ""; or en: Cannot use object of type stdClass as array in $jsonObj[$k1][$k2] = "";

  • 1

    I edited again, I didn’t see that they were objects.

  • Thank you, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.