2014-01-24 55 views
0

我在試圖做的是將以下數組中的foreach移出,以便每個用戶角色都可以是select中的HTML選項。如果用戶正在編輯,我也試圖嘗試預先選擇一個選項。嘗試一條foreach語句

用戶角色陣列

Dump => array(5) { 
    [0] => object(stdClass)#26 (2) { 
     ["user_role_id"] => string(1) "1" 
     ["user_role_name"] => string(5) "Guest" 
    } 
    [1] => object(stdClass)#27 (2) { 
     ["user_role_id"] => string(1) "2" 
     ["user_role_name"] => string(11) "Public User" 
    } 
    [2] => object(stdClass)#28 (2) { 
     ["user_role_id"] => string(1) "3" 
     ["user_role_name"] => string(9) "Moderator" 
    } 
    [3] => object(stdClass)#29 (2) { 
     ["user_role_id"] => string(1) "4" 
     ["user_role_name"] => string(13) "Administrator" 
    } 
    [4] => object(stdClass)#30 (2) { 
     ["user_role_id"] => string(1) "5" 
     ["user_role_name"] => string(20) "Master Administrator" 
    } 
} 

<?php 
dump_exit($user_roles); 
foreach($user_roles AS $key => $value) 
{ 
    foreach ($value AS $role) 
    { 

    } 
    //echo '<option value="'.$key.'"'. $value->user_role_id == $key ? " selected=\"selected\"":"".'>'.$value->user_role_name.'</option>'; 
} 
?> 

UPDATE: 
I need it to see if $user_account object is present on the page because if it is that means that the user is being edited and I need it to match the user's current user_status_id with the option that fits in the dropdown. 

Dump => object(stdClass)#31 (13) { 
    ["user_role_id"] => string(1) "5" 
} 

回答

2

只是爲了完成回答我上面,版本預選的作用。

if(isset($user_account)) $selected= $user_account->user_role_id; 
else $selected = null; 
echo '<select>'; 
foreach ($user_roles as $role) { 
    echo "<option value='{$role->user_role_id}'"; 
    if($role->user_role_id==$selected) echo 'selected'; 
    echo ">{$role->user_role_name}</option>"; 
} 
echo '</select>'; 
+0

檢查編輯。 – user2576961

+0

再加上我想出了一個語法錯誤與你的偉大的答案。 – user2576961

+0

我讓大括號中的if語句,我的壞。 –

1
<?php 
echo '<select name="user_role">'; 
foreach($user_roles as $role) { 
    echo "<option value='{$role->user_role_id}'>{$role->user_role_name}</option>"; 
} 
echo '</select>'; 
?> 
+0

查看最新的更新。 – user2576961

+0

更新內容有哪些變化? –