Riley Osborne
Riley Osborne

Reputation: 35

Need To Group Results of foreach()

foreach ($mgrAccounts as $mgrAccount) {
    $mgrAccNames  = $mgrAccount['account_name'];
    $userAccNames = $userRow['account_name'];
    $userAccNames = explode(',', str_replace(['{', '}', '"'], "", $userAccNames));
    $mgrAccNames  = explode(',', str_replace(['{', '}', '"'], "", $mgrAccNames));
    $accounts     = array_intersect($userAccNames, $mgrAccNames);

    if (!empty($accounts)) {
        $tableStr .= "<tr>";
        $tableStr .= "<td><select name='selectAccounts' id='selectAccounts'>";
        foreach ($accounts as $account) {
            $tableStr .= "<option>{$account}</option>";
        }
        $tableStr .= "</select></td>";
        $tableStr .= "<td><a href='/reset_password.php'>Password Reset</a></td>";
        $tableStr .= "</tr>";
    }
}

I need to be able to have a dropdown with each account as an option in it. Currently, it is creating a new option for each account. How can I group everything together to put into the options dropdown?

Upvotes: 1

Views: 24

Answers (1)

failedCoder
failedCoder

Reputation: 1424

Just open and close your table outside the loop

$tableStr .= "<tr>";
$tableStr .= "<td><select name='selectAccounts' id='selectAccounts'>";
foreach ($mgrAccounts as $mgrAccount) {
    $mgrAccNames = $mgrAccount['account_name'];
    $userAccNames = $userRow['account_name'];
    $userAccNames = explode(',', str_replace(['{', '}', '"'], "", $userAccNames));
    $mgrAccNames = explode(',', str_replace(['{', '}', '"'], "", $mgrAccNames));
    $accounts = array_intersect($userAccNames, $mgrAccNames);

    if (!empty($accounts)) {


         foreach ($accounts as $account) {
             $tableStr .= "<option>{$account}</option>";
         }


     }
}
$tableStr .= "</select></td>";
$tableStr .= "<td><a href='/reset_password.php'>Password Reset</a> 
</td>";
$tableStr .= "</tr>";

Upvotes: 1

Related Questions