php 在数组中使用 If-else

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6665068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:57:20  来源:igfitidea点击:

Using an If-else within an array

phparraysif-statement

提问by Michael

Hi guys I have no idea if this is possible or if there is another way of doing it but any help would be appreciated. What I'm trying to do is turn off arrays individually. So I have this..

嗨,伙计们,我不知道这是否可行,或者是否有其他方法可以做到,但任何帮助将不胜感激。我想要做的是单独关闭阵列。所以我有这个..

<?php
$arrLayout = array(
    "section1" => array(

        "wLibrary" => array(
            "title" => "XBMC Library",
            "display" => ""
        ),

        "wControl" => array(
            "title" => "Control",
            "display" => ""
        )
        )
            )
?>

What I want is this

我想要的是这个

<?php

$LibraryStatus='true'

$arrLayout = array(
    "section1" => array(

                  if $LibraryStatus='true' (

        "wLibrary" => array(
            "title" => "XBMC Library",
            "display" => ""
        ),
                  else blank.      

              if $ControlStatus='true' (

    "wControl" => array(
            "title" => "Control",
            "display" => ""
        )
    )
            )
?>

If its false then it will also be blank obviously. Is it possible to have an if then inside an array controlling another array? If so how would it work? This is just part of the array there are more options and sections I just took those out for simplicity as its easy to scale once I understand how to do it once.

如果它是假的,那么它显然也将是空白的。是否可以在控制另一个数组的数组中使用 if then ?如果是这样,它将如何工作?这只是数组的一部分,还有更多的选项和部分,为了简单起见,我只是将它们取出来,因为一旦我理解了如何做一次,它就很容易扩展。

Thanks

谢谢

回答by Kokos

Yes, this is possible using a certain shorthand:

是的,这可以使用某种速记:

<?php

$LibraryStatus = $ControlStatus = true;

$arrLayout = array(
             "section1" => array(
             ($LibraryStatus ? array("wLibrary" => array("title"   => "XMBC Library",
                                                         "display" => "")) : false),
             ($ControlStatus ? array("wControl" => array("title"   => "Control",
                                                         "display" => "")) : false)));

print_r($arrLayout);

?>

It works like this:

它是这样工作的:

if($a == $b){ echo 'a'; }else{ echo 'b'; }

is equal to

等于

echo $a == $b ? 'a' : 'b';

If you use this shorthand it will always return the output, so you can put it between brackets and put it inbetween the array.

如果你使用这个简写,它总是会返回输出,所以你可以把它放在括号之间,然后放在数组之间。

http://codepad.org/cxp0M0oL

http://codepad.org/cxp0M0oL

But for this exact situation there are other solutions as well.

但是对于这种确切的情况,还有其他解决方案。

回答by Ostin

Inside an array you can use ternary operator:

在数组中,您可以使用三元运算符:

$a = array(
    'b' => $expression == true ? 'myWord' : '';
);

But in your example better way is to move if-statement outside your array.

但是在您的示例中,更好的方法是将 if 语句移到数组之外。

回答by Jon

You are complicating things needlessly.

你在不必要地把事情复杂化。

If the condition and the values you want to assign are simple enough, you can use the ternary operator (?:) like so:

如果您要分配的条件和值足够简单,则可以?:像这样使用三元运算符 ( ):

$condition = true;
$arrLayout = array(
    "section1" => $condition ?
                     array(
                         "wLibrary" => array(
                             "title" => "XBMC Library",
                             "display" => ""
                         )
                     ) : false,
)

However, this is not very readable even for simple cases and I would call it a highly questionable practice. It's much better to keep it as simple as possible:

但是,即使对于简单的情况,这也不是很可读,我认为这是一种非常值得怀疑的做法。最好让它尽可能简单:

$condition = true;
$arrLayout = array(
    "section1" => false
);

if($condition) {
    $arrLayout["section1"] = array(
                                  "wLibrary" => array(
                                     "title" => "XBMC Library",
                                     "display" => ""
                                  )
                             );
}

回答by mwotton

Another way is to include the logic in either a function or via an include file.

另一种方法是将逻辑包含在函数中或通过包含文件。

With function:

带功能:

function section1Function($status = false){
    if ($status){
        return array(
            "wLibrary" => array(
                "title" => "XBMC Library",
                "display" => ""
            )
        );
    } else {
        return array(
            "wControl" => array(
                "title" => "Control",
                "display" => ""
            )
        );
    }
}

$LibraryStatus='true'

$arrLayout = array(
    "section1" => section1Function($LibraryStatus),
)

?>

With include file:

使用包含文件:

<?php


$LibraryStatus='true'

$arrLayout = array(
    "section1" => require( dirname(__FILE__) .'/section1Layout.php'),
)

?>

section1Layout.php:

section1Layout.php:

<?php
if ($LibraryStatus){
    return array(
        "wLibrary" => array(
            "title" => "XBMC Library",
            "display" => ""
        )
    );
} else {
    return array(
        "wControl" => array(
            "title" => "Control",
            "display" => ""
        )
    );
}
?>

回答by Dunhamzzz

What you are suggesting is not possible. You would need to add the variables base on the if/else conditional after you have made the array.

你的建议是不可能的。在创建数组后,您需要根据 if/else 条件添加变量。

For example:

例如:

$arrLayout = array();

if($LibraryStatus) {
    $arrLayout['section1'] = array("wLibrary" => array(
            "title" => "XBMC Library",
            "display" => ""
        ));
}

This still rather untidy because of your array structure, I'd try eliminating some keys if you can, for example do you need section1? You could just let PHP add a numerical key by doing $arrLayout[] = array(..), which create a new 'row' in the array which you can still loop through.

由于您的数组结构,这仍然相当不整洁,如果可以,我会尝试消除一些键,例如您需要section1吗?您可以让 PHP 通过执行添加一个数字键$arrLayout[] = array(..),这会在数组中创建一个新的“行”,您仍然可以循环遍历该行。

回答by Ilia Rostovtsev

Encountered this problem, when was setting up PDO debugmode, that is dependent on config settings.

遇到这个问题,什么时候设置PDO调试模式,就是依赖config设置。

Examples above were great but a bit ambiguous, so I decided to write another, simple example of how to do it:

上面的例子很好,但有点模棱两可,所以我决定写另一个简单的例子来说明如何做到这一点:

array(
    'key' => $variable ? 'Sets certain value if $variable === true' : 'Sets certain value if $variable === false'
);

回答by jenovachild

In a way, yes.

在某种程度上,是的。

You can't place it where you've asked (directly after the opening of an array) You can't use an if statement. You can use ternary (condition) ? true : false

你不能把它放在你要求的地方(直接在数组打开之后)你不能使用 if 语句。您可以使用三元(条件)?真假

<?php

$LibraryStatus = 'true';

$array = array(
    "section1" => ($LibraryStatus == 'true') ? array("wLibrary" => array("title" =>     "Title","display" => "")) : array()  
);

?>

回答by Manuel

You could use push?

你可以用推吗?

<?php

$LibraryStatus='true'

$arrLayout = array();
if ($LibraryStatus=='true') {
push($arrLayout["section1"], array(
        "wLibrary" => array(
            "title" => "XBMC Library",
            "display" => ""
        ));
}
?>

回答by wanovak

No, you cannot have an if-elseblock in the middle of an array declaration. You can, however, manipulate the array in different ways to achieve the desired result. See array functions.

不,你不能if-else在数组声明的中间有一个块。但是,您可以以不同的方式操作数组以获得所需的结果。请参阅数组函数

回答by Nicola Peluchetti

You can do:

你可以做:

$emptyArray = array();
$arrLayout = array("section1" => $emptyArray);

$LibraryStatus= true ;
if ($LibraryStatus=== true) {
     $arrLayout["section1"]["wlibrary"] =  array("title" => "XBMC Library","display" => "" );
}