【问题标题】:How can I add a condition inside a php array?如何在 php 数组中添加条件?
【发布时间】:2022-05-05 17:36:05
【问题描述】:

这是数组

$anArray = array(
   "theFirstItem" => "a first item",
   if(True){
     "conditionalItem" => "it may appear base on the condition",
   }
   "theLastItem"  => "the last item"

);

但是我得到了 PHP Parse 错误,为什么我可以在数组中添加一个条件,发生了什么??:

PHP Parse error:  syntax error, unexpected T_IF, expecting ')'

【问题讨论】:

    标签: php arrays syntax


    【解决方案1】:

    很遗憾,这根本不可能。

    如果有该项目但具有 NULL 值是可以的,使用这个:

    $anArray = array(
       "theFirstItem" => "a first item",
       "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
       "theLastItem"  => "the last item"
    );
    

    否则你必须这样做:

    $anArray = array(
       "theFirstItem" => "a first item",
       "theLastItem"  => "the last item"
    );
    
    if($condition) {
       $anArray['conditionalItem'] = "it may appear base on the condition";
    }
    

    如果顺序很重要,那就更丑了:

    $anArray = array("theFirstItem" => "a first item");
    if($condition) {
       $anArray['conditionalItem'] = "it may appear base on the condition";
    }
    $anArray['theLastItem'] = "the last item";
    

    不过,你可以让它更易读:

    $anArray = array();
    $anArray['theFirstItem'] = "a first item";
    if($condition) {
       $anArray['conditionalItem'] = "it may appear base on the condition";
    }
    $anArray['theLastItem'] = "the last item";
    

    【讨论】:

    • 第二个好像亮了
    • $anArray = array( "theFirstItem" => "a first item", "conditionalItem" => $condition ? "它可能基于条件出现" : NULL, "theLastItem" => "最后一项”);非常适合我,谢谢
    【解决方案2】:

    如果您正在创建一个纯关联数组,并且键的顺序无关紧要,您始终可以使用三元运算符语法有条件地命名键。

    $anArray = array(
        "theFirstItem" => "a first item",
        (true ? "conditionalItem" : "") => (true ? "it may appear base on the condition" : ""),
        "theLastItem" => "the last item"
    );
    

    这样,如果满足条件,则键与数据一起存在。如果不是,它只是一个带有空字符串值的空键。但是,鉴于已经有很多其他答案,可能会有更好的选择来满足您的需求。这并不完全干净,但如果您正在处理一个具有大型数组的项目,它可能比打破数组然后添加更容易;特别是如果数组是多维的。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      $anArray = array(1 => 'first');
      if (true) $anArray['cond'] = 'true';
      $anArray['last'] = 'last';
      

      然而,你想要的却是不可能的。

      【讨论】:

      【解决方案4】:

      这里没有任何魔法可以提供帮助。你能做的最好的就是:

      $anArray = array("theFirstItem" => "a first item");
      if (true) {
          $anArray["conditionalItem"] = "it may appear base on the condition";
      }
      $anArray["theLastItem"]  = "the last item";
      

      如果你不特别关心物品的顺序,它会更容易忍受:

      $anArray = array(
          "theFirstItem" => "a first item",
          "theLastItem"  => "the last item"
      );
      if (true) {
          $anArray["conditionalItem"] = "it may appear base on the condition";
      }
      

      或者,如果顺序确实很重要并且条件项不止几个,您可以这样做,这可能被认为更具可读性:

      $anArray = array(
          "theFirstItem" => "a first item",
          "conditionalItem" => "it may appear base on the condition",
          "theLastItem"  => "the last item",
      );
      
      if (!true) {
          unset($anArray["conditionalItem"]);
      }
      
      // Unset any other conditional items here
      

      【讨论】:

        【解决方案5】:

        如果你有具有不同键的关联数组,试试这个:

        $someArray = [
            "theFirstItem" => "a first item",
        ] + 
        $condition 
            ? [
                "conditionalItem" => "it may appear base on the condition"
              ] 
            : [ /* empty array if false */
        ] + 
        [
            "theLastItem" => "the last item",
        ];
        

        如果数组不关联,则为 this

        $someArray = array_merge(
            [
                "a first item",
            ],
            $condition 
                ? [
                    "it may appear base on the condition"
                  ] 
                : [ /* empty array if false */
            ], 
            [
                "the last item",
            ]
        );
        

        【讨论】:

          【解决方案6】:

          您可以像这样一次分配所有值并过滤数组中的空键:

          $anArray = array_filter([
             "theFirstItem" => "a first item",
             "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
             "theLastItem"  => "the last item"
          ]);
          

          这使您可以避免事后的额外条件,保持键顺序,并且它具有相当的可读性。这里唯一需要注意的是,如果您有其他虚假值 (0, false, "", array()),它们也会被删除。在这种情况下,您可能希望添加一个回调来显式检查NULL。在以下情况下,theLastItem 不会被无意过滤:

          $anArray = array_filter([
              "theFirstItem" => "a first item",
              "conditionalItem" => $condition ? "it may appear base on the condition" : NULL,
              "theLastItem"  => false,
          ], function($v) { return $v !== NULL; });
          

          【讨论】:

            【解决方案7】:

            你可以这样做:

            $anArray = array(
                "theFirstItem" => "a first item",
                (true ? "conditionalItem" : "EMPTY") => (true ? "it may appear base on the condition" : "EMPTY"),
                "theLastItem" => "the last item"
            );
            

            如果条件为假,则取消设置 EMPTY 数组项

            unset($anArray['EMPTY']);
            

            【讨论】:

              【解决方案8】:

              它非常简单。创建包含基本元素的数组。然后将条件元素添加到数组中。如果需要,现在添加其他元素。

              $anArray = array(
                  "theFirstItem" => "a first item"
              );
              
              if(True){
                  $anArray+=array("conditionalItem" => "it may appear base on the condition");
              }
              
              $more=array(
                  "theLastItem"  => "the last item"
              ); 
              
              $anArray+=$more;
              

              您修改此代码以使其更短,我刚刚给出了详细的代码以使其自我解释。 没有 NULL 元素,没有空字符串,把你的项目放在你想要的任何地方,没有麻烦。

              【讨论】:

                【解决方案9】:

                你可以使用array_merge

                $result = array_merge(
                    ['apple' => 'two'],
                    (true ? ['banana' => 'four'] : []),
                    (false ? ['strawberry' => 'ten'] : [])
                );
                
                print_r($result);
                
                // Output:
                /* 
                Array
                (
                    [apple] => 'two'
                    [banana] => 'four'
                ) 
                */
                

                array_merge 的缺点:具有数字键的数组中的值将使用从结果数组中的零开始递增的键重新编号。您可以改用联合运算符来维护原始数字键

                或者使用数组联合运算符

                $result = ['apple' => 'two'] + (true ? ['banana' => 'four'] : []) + (false ? ['strawberry' => 'ten'] : []);
                
                print_r($result);
                
                // Output:
                /* 
                Array
                (
                    [apple] => 'two'
                    [banana] => 'four'
                ) 
                */
                

                注意:使用联合运算符时,请记住,对于两个数组中都存在的键,左侧数组中的元素将被使用,而右侧数组中的匹配元素将被忽略。

                【讨论】:

                猜你喜欢
                • 2021-11-29
                • 1970-01-01
                • 1970-01-01
                • 2017-08-24
                • 2011-01-01
                • 1970-01-01
                • 2012-01-17
                • 1970-01-01
                • 2014-12-14
                相关资源
                最近更新 更多