使用关联数组,HTML表单和PHP foreach;表达式引擎


Working with associative arrays, HTML form and PHP foreach & Expression Engine

我有一个HTML表单,看起来像这样…

<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}
<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}
<input type="checkbox" name="comp[{url_title}][check]" value="Yes" class="checkbox" />
{if question}<input type="text" name="comp[{url_title}][answer]" value="" />{/if}

我在$_POST上的vardump是这样的…

array(3) {
  ["some-competition-title"]=>
  array(1) {
    ["check"]=>
    string(3) "Yes"
  }
  ["third-competition"]=>
  array(2) {
    ["check"]=>
    string(3) "Yes"
    ["answerswer"]=>
    string(6) "asdasd"
  }
  ["another-comp-title"]=>
  array(1) {
    ["check"]=>
    string(3) "Yes"
  }
}

我的foreach循环是这样的

foreach ($_POST['comp'] as $topkey => $input) {
    foreach ($input as $key => $value) {
        echo "<div style='"background:#fff; padding:10px;'">";
        echo "$topkey | $value ";
        echo "<br>";
        echo "</div>";
    }
}

返回

some-competition-title | Yes 
third-competition | Yes 
third-competition | asdasd 
another-comp-title | Yes 

OK -我试图传递foreach循环,所以它会结合复选框和答案,如果数组的名称(url-title)是相同的,所以本质上我希望它返回这个。

some-competition-title | Yes 
third-competition | Yes | asdasd 
another-comp-title | Yes 

与我上面的相反。任何帮助都会非常感激。谢谢。

您只需要将子数组的值合并为一个值。

foreach ($_POST['comp'] as $topkey => $input) 
{
    // get the values of the subarray and assign them
    // to $value 
    $value = implode(' | ', array_values($input));
    echo "<div style='"background:#fff; padding:10px;'">";
    echo "$topkey | $value ";
    echo "<br>";
    echo "</div>";
}

如何使用一个for循环:

foreach ($_POST['comp'] as $topkey => $input) {
    echo "<div style='"background:#fff; padding:10px;'">";
    $value = '';
    if (isset($input['check']) && isset($input['answer'])) {
        $value = $topkey . " | " . $input['check'] . " | " . $input['answer'];
    } elseif (isset($input['check'])) {
        $value = $topkey . " | " . $input['check'];
    }
    echo "$topkey | $value ";
    echo "<br />";
    echo "</div>";
}

检查数组中是否同时存在checkanswer,如果是,则第一个if条件为真并取值,否则如果仅存在check,则执行elseif