Filling missing result index of a select with 0

Asked

Viewed 50 times

0

I make a select in the database from which I get a array data. With this, I do the following foreach in the same:

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, it happens that one of the select’s Dexes comes with no results, in the case of index Z, does not exist. When this happened, I wanted to put the values of this nonexistent index as 0, thus creating it and assigning the value 0, because I need it to perform some accounts that does not enter the question. So far I haven’t been able to formulate any logic to accomplish the same.

1 answer

2


Hello, you can check if the index is set before assigning the value using the function isset along with ternary operators. At 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 take 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

Browser other questions tagged

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