简体   繁体   English

php中的`IF语句`array()`函数

[英]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. 反过来,我希望以某种方式根据NON Null结果创建排名。

SQL Query returns: SQL Query返回:

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

My PHP: 我的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() ? 你试过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. 更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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