Filling index of non-existent results of a select with 0

0

I make a select in the database which returns me a array of data. With this, I make the following foreach on it:

foreach ($resultado4 as $key => $value7) {  
    $array6[$value7['carteira'].'flores'] = $value7['floresqtd'];
    $array6[$value7['carteira'].'isa'] = $value7['isaqtd'];
    $array6[$value7['carteira'].'uni'] = $value7['uniqtd'];
    $array8[$value7['carteira'].'flores'] = $value7['floresvalor'];
    $array8[$value7['carteira'].'isa'] = $value7['isavalor'];
    $array8[$value7['carteira'].'uni'] = $value7['univalor'];
}

Sometimes, one of the indexes of the select come with no result, in the case of the index Z, does not exist. When this happened, I wanted to put the value of this nonexistent index as 0, thus creating it and assigning the value 0, since I need it to perform some accounts that do not enter into the question. So far I have not been able to formulate any logic to accomplish the same thing.

    
asked by anonymous 01.06.2018 / 19:37

1 answer

2

Hello, you can check if the index is set before assigning the value using the isset function. along with ternary operators . This link here has more information.

// php <= 5.6
foreach ($resultado4 as $key => $value7) {
    $array6[$value7['carteira'].'flores'] = isset($value7['floresqtd']) ? $value7['floresqtd'] : 0;
    $array6[$value7['carteira'].'isa'] = isset($value7['isaqtd']) ? $value7['isaqtd'] : 0;
    $array6[$value7['carteira'].'uni'] = isset($value7['uniqtd']) ? $value7['uniqtd'] : 0;
    $array8[$value7['carteira'].'flores'] = isset($value7['floresvalor']) ? $value7['floresvalor'] : 0.0;
    $array8[$value7['carteira'].'isa'] = isset($value7['isavalor']) ? $value7['isavalor'] : 0;
    $array8[$value7['carteira'].'uni'] = isset($value7['univalor']) ? $value7['univalor'] : 0;
}

// php >= 7.x
foreach ($resultado4 as $key => $value7) {
    $array6[$value7['carteira'].'flores'] = $value7['floresqtd'] ?? 0;
    $array6[$value7['carteira'].'isa'] = $value7['isaqtd'] ?? 0;
    $array6[$value7['carteira'].'uni'] = $value7['uniqtd'] ?? 0;
    $array8[$value7['carteira'].'flores'] = $value7['floresvalor'] ?? 0;
    $array8[$value7['carteira'].'isa'] = $value7['isavalor'] ?? 0;
    $array8[$value7['carteira'].'uni'] = $value7['univalor'] ?? 0;
}

Another option would also be to change the query to get the value of the column if it is not null otherwise it takes a value you set in case 0. For example:

SELECT id, 
   IF(valor IS NOT NULL, valor, 0)
FROM tabela
    
01.06.2018 / 20:35