简体   繁体   English

将元素添加到具有条件的数组

[英]Add element to array with condition

I have a foreach statement with an if statement at his top then a switch statement我有一个 foreach 语句,在他的顶部有一个 if 语句,然后是一个 switch 语句

<?php
foreach(self::CRITS as $crit){
    if( $crit == 'some condition') {
     $myVar = "size => 10";
    }

    switch($crit) {
        case1:
            $agg[$crit] = [
                "terms" => [
                    "field" => $crit
                    $myVar
                ]
            ];
            // expected if $crit == 'some condition' true
            //$agg[$crit] = [
            //    "terms" => [
            //        "field" => $crit
            //        "size" => 10
            //    ]
            //];
            // expected if $crit == 'some condition' false
            //$agg[$crit] = [
            //    "terms" => [
            //        "field" => $crit
            //    ]
            //];

        break;
        // more cases with same behavior

    }
}

According to the IF statement I want add $myVar as a new key/value pair to $agg[$crit]["terms"] .根据 IF 语句,我想将$myVar作为新的键/值对添加到$agg[$crit]["terms"]

I can do it in each case of my switch statement like我可以在我的 switch 语句的每种情况下都这样做

case1:
$agg[$crit] = [
    "terms" => [
        "field" => $crit
    ]
];

if($crit == 'some condition') {
    $agg[$crit]["terms"]["size"] = 10;
}
break;

but the IF statement will be duplicate.但是 IF 语句将是重复的。

There is a way in PHP to do that? PHP 有办法做到这一点吗?

For example:例如:

if( $crit == 'some condition') {
    $myKey = 'size';
    $myValue = 10;
}

$agg[$crit] = [
    "terms" => [
        "field" => $crit,
        $myKey => $myValue,
    ]
]

Unfortunetly it seems impossible to be done that way.不幸的是,这样做似乎是不可能的。

So I figured out with a quite simple workaround and use of array_filter所以我想出了一个非常简单的解决方法并使用 array_filter

<?php
foreach(self::CRITS as $crit){
    $condition = ( $crit === 'some condition' ? true : false);

    switch($crit) {
        case1:
           $agg[$crit] = [
               "terms" => array_filter([
                   "field" => $crit
                   "size" => ($condition ? $size[$crit] : NULL)
            ],function($v){
                return $v !== NULL;
            })
        ];
        break;
        // more cases with same behavior
    }
}

array filter will remove all size fields with value of NULL数组过滤器将删除所有值为 NULL 的大小字段

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

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