2014-01-24 4 views
0

내가하려고하는 것은 각 사용자 역할이 선택 안에 HTML 옵션이 될 수 있도록 다음 배열에서 foreach를 만드는 것입니다. 나는 또한 편집중인 사용자 인 경우 미리 선택된 옵션을 사용하려고 시도하고있다.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

업데이트가 변경되었습니다. –

관련 문제