2011-12-07 87 views
0

我需要把一個條件,當我創建我的數組的一個元素如果條件關聯數組

foreach ($score as $item): 
    if ($item['subject_id'] == "3"){ 
     $file_data_array[] = array(
      "y" => $item['result'], 
    ////Need condition here/////////////////////////////// 
      "color" => '#FFF'     
      ); 
     } 
endforeach; 

所以我需要一個像

if ($item['confirmed'] == 1) { 
    "color" => '#FFF' 
} else { 
    "color" => '#000' 
} 

這樣的條件,因爲我們不能把一個if在一個數組中,我該如何處理我的狀況?

回答

4

嘗試並使用ternary if

foreach ($score as $item): 
    if($item['subject_id'] == "3"){ 
     $file_data_array[] = array(
      "y" => $item['result'], 
      "color" => ($item['confirmed'] == 1 ? '#FFF': '#000') 
     ); 
endforeach; 
+0

THX!它的工作! :) – user1029834

2
foreach ($score as $item): 
if($item['subject_id'] == "3"){ 
    if($item['confirmed'] == 1) { 
     $color = '#FFF'; 
     } else { 
     $color = '#000'; 
     }  
    $file_data_array[] = array(
     "y" => $item['result'], 
     "color" => $color); 
endforeach; 
3
"color" => ($item['confirmed']==1 ? "#FFF" : "#000") 
0
<?php 
$login_detail=array(0=>array("sumit","8101"),1=>array("ashwani","9526"),2=>array("parmod","2592"),3=>array("jitendra","5792"),4=>array("umesh","5555")); 
foreach($login_detail as $value) 
{ 
    foreach($value as $value2) 
    { 
     echo $value2." &nbsp;&nbsp;"; 
    } 
    echo "<br>"; 
} 
$username=$_POST['txtusername']; 
$password=$_POST['txtpassword']; 
if($username==$login_detail && $password==$value) 
{ 
    header("location: dashbord.php"); 
} 
else 
{ 
    header("location: loginexample.php?msg=user name or password is wrong"); 
} 
+0

解釋將不勝感激 – Populus