PHP foreach如果条件

时间:2012-11-11 21:13:36

标签: php arrays if-statement foreach

这应该很容易,但我似乎无法让它发挥作用。我有一个多维数组,我不想通过数组迭代并检查一个特定的值。如果值等于字符串,则回显出数组的值。

这是数组和两个值(完整数组有更多):

$users = array( 
    "username01" => array("fullname" => "Firstname Lastname",
                            "status" => "Online"),
    "username02" => array("fullname" => "Firstname Lastname",
                            "status" => "Offline")
);

我不想echo出每个“在线”用户的全名。这是我今天使用的,但它不起作用:

$string = "Online";
foreach ($users as $username => $data) {
    $fullname = $data["fullname"];
    $status   = $data["status"];

    echo $status."= ";
    if ($status == $string) { 
        echo "Yes"; 
    } else { 
        echo "No"; 
    }
      echo "<br>";
}

如果我回显$fullname$status,则会打印出正确的数据。但由于某种原因,IF声明不起作用。如果用户处于离线状态,则回显为“否”,但如果用户处于在线状态,则根本没有回声。

编辑 - 解决
使用引号和$ data [...]更新了数组键,如下所示。我发现了一个导致错误输出的拼写错误。感谢您的帮助。

4 个答案:

答案 0 :(得分:3)

这对我有用:

<?php 

    //you forgot to enclose your keys by Single Quote (')
    $users = array( 
    "username01" => array('fullname' => "Firstname Lastname",
                'status' => "Online"),
    "username02" => array('fullname' => "Firstname Lastname",
                'status' => "Offline")
);

    $string = "Online";
    foreach ($users as $username => $data) {
      //Notice this line
      //$username is the key 
      //at the first iteraiton it will be uername01
      //$data holds the array of username index in the array named $users
      $fullname = $data["fullname"];
      $status = $data['status'];
      if($status == $string) { echo "Yes"; } else { echo "No"; }
    }

?>

浏览foreach in php以了解有关foreach的更多详情。

希望有所帮助。快乐的编码。

答案 1 :(得分:2)

可能它与数组定义中“fullname”和“status”周围缺少的引号有关。您打印的代码正在运行,但它会发出警告。

尝试如下:

<?php
$users = array( 
    "username01" => array("fullname" => "Firstname Lastname",
                            "status" => "Online"),
    "username02" => array("fullname" => "Firstname Lastname",
                            "status" => "Offline")
);

答案 2 :(得分:1)

奇怪 - 看起来应该有用......

试试这个:

$users = array( 
    "username01" => array(  'fullname' => "Firstname Lastname",
                            'status' => "Online"),
    "username02" => array(  'fullname' => "Firstname Lastname",
                            'status' => "Offline")
     );

foreach ( $users as $user )
{
    if( strcasecmp( 'online', $user['status'] ) == 0 )
    {
        echo $user['fullname'] .': Online';
    }
    else
    {
        echo $user['fullname'] .': Offline';
    }
}

答案 3 :(得分:1)

你的问题是你的阵容。 试一试。

$users = array( 
    "username01" => array(  "fullname" => "Firstname Lastname",
                            "status" => "Online"),
    "username02" => array(  "fullname" => "Firstname Lastname",
                            "status" => "Offline")
     );

您忘记了"status fullname。 适用于我当地的XAMPP。