简体   繁体   中英

php IF statements inside `array()` function

I am trying to set an array based on query results that are NOT Null. In turn I hope to somehow create a ranking based on the NON Null results.

SQL Query returns:

Comp1    Comp2   Comp3   Comp4   Comp5   Comp6   Comp7   Comp8   Comp9
NULL     NULL    226.97   274    NULL    208     189     NULL    198.99

My PHP:

$COMP1 = $rankresult['Comp1'];
$COMP2 = $rankresult['Comp2'];
$COMP3 = $rankresult['Comp3'];
$COMP4 = $rankresult['Comp4'];
$COMP5 = $rankresult['Comp5'];
$COMP6 = $rankresult['Comp6'];
$COMP7 = $rankresult['Comp7'];
$COMP8 = $rankresult['Comp8'];
$COMP9 = $rankresult['Comp9'];

This does not work as I am trying to only put in variables that are NOT Null:

$myarray = 'array(
        if(!empty($COMP1)){ 
        $COMP1,}
        if(!empty($COMP2)){ 
        $COMP2,}
        if(!empty($COMP3)){ 
        $COMP3,}
        if(!empty($COMP4)){ 
        $COMP4,}
        if(!empty($COMP5)){ 
        $COMP5,}
        if(!empty($COMP6)){ 
        $COMP6,}
        if(!empty($COMP7)){ 
        $COMP7,}
        if(!empty($COMP8)){ 
        $COMP8,}
        if(!empty($COMP9)){ 
        $COMP9})';

Desired output:

$myarray = array(226.97,274,208,189,198.99)

Have you tried array_filter() ?

$result = array_filter($rankresult);

Result:

array(
    "comp3"=>226.97,
    "comp4"=>274,
    "comp6"=>208,
    "comp7"=>189,
    "comp9"=>198.99
)

Have you though about using a loop?

If you have the size of the result query, you can do something like this:

$myarray=new array();
for ($ix=1; $ix<$num_rows; $ix++) {
    if (${COMP.$ix}!=NULL)
        array_push($myarray,${COMP.$ix});
}

Updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM