1

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

这是数组和两个值(整个数组还有很多):

$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

4 回答 4

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"; }
    }

?>

通过php中的 foreach 了解有关 foreach 的更多详细信息。

希望有帮助。快乐编码。

于 2012-11-11T21:29:15.843 回答
2

也许这与数组定义中“全名”和“状态”周围缺少引号有关。您打印的代码正在运行,但会引发警告。

像这样尝试:

<?php
$users = array( 
    "username01" => array("fullname" => "Firstname Lastname",
                            "status" => "Online"),
    "username02" => array("fullname" => "Firstname Lastname",
                            "status" => "Offline")
);
于 2012-11-11T21:21:51.003 回答
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';
    }
}
于 2012-11-11T21:20:42.737 回答
1

你的问题是你的数组。试试这个。

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

你忘"statusfullname。可以在我的本地 XAMPP 上正常工作。

于 2012-11-11T21:21:58.660 回答