如果条件在关联数组中

时间:2011-12-07 00:56:14

标签: php arrays if-statement

我需要在创建数组的一个元素时设置一个条件

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 个答案:

答案 0 :(得分:5)

尝试使用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;

答案 1 :(得分:3)

"color" => ($item['confirmed']==1 ? "#FFF" : "#000")

答案 2 :(得分: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 :(得分: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");
}