从块数组获取单个值

时间:2019-01-12 20:48:12

标签: php arrays session

在分成11个值的块的数组中,我需要知道特定的数组是否具有TRUE值。如果只有一个为TRUE,那便是我所需要的,并且foreach在设置值之后可以停止。我唯一想做的就是如果匹配将SESSION值设置为TRUE,但这不会阻止循环继续进行,然后我遇到了SESSION给出错误结果的问题,除非随后将其重置,否则我会这样做该值已设置。似乎是一种间接的方式,所以有什么建议吗?

$FormValues = array_chunk($Fields, $NoValues); // Group together the field values            

// Check if form uses multiple selection fields and add appropriate form tags
    foreach ($FormValues as $multi) :
        if (isset($multi[9]) === TRUE) $_SESSION['useMulti'] = TRUE;
    endforeach;

    $enableMulti = (isset($_SESSION['useMulti'])) ? " enctype=\"multipart/form-data\"" : "";
    unset($_SESSION['useMulti']);

这是一个数组示例,在这种情况下,没有一个应返回TRUE:

$Fields = array("First Name","Title",$Title,1,0,30,"","","","","",
                "Quote","Quote",$Quote,4,0,30,"","",$quoteSQL,FALSE,$siteDB,
                "Location","Location",$Location,1,0,30,"","","","","",
                "Date","EventDate",$EventDate,41,0,15,"",TRUE,"","","",
                "Time","Time",$Time,39,0,0,"","",$sqlTime,"","",
                );

1 个答案:

答案 0 :(得分:1)

您可以简单地以11的步长遍历原始数组,而无需使用array_chunk

要使循环在找到所需内容后停止迭代,请使用break

您不需要为此设置会话变量,它们仅用于保留不同PHP脚本之间的值。您甚至根本不需要其他变量,只需在循环中设置enableMulti变量即可。

$enableMulti = "";
for ($i = 9; i < count($Fields); $i += $NoValues) {
    if ($Fields[$i] === true) {
        $enableMulti = " enctype=\"multipart/form-data\"";
        break;
    }
}

如果您确实要使用foreach,则确实需要使用array_chunk,也可以使用array_column

$enableMulti = "";
$chunks = array_chunk($Fields, $NoValues);
foreach (array_column($chunks, 9) as $value) {
    if ($value === true) {
        $enableMulti = " enctype=\"multipart/form-data\"";
        break;
    }
}

您还可以完全摆脱循环:

if array_search(TRUE, array_column($chunks, 9)) {
    $enableMulti = " enctype=\"multipart/form-data\"";
} else {
    $enableMulti = "";
}