dqoqnmb163241 2012-11-11 21:13
浏览 23
已采纳

PHP foreach如果条件[关闭]

This should be easy, but I can´t seem to get it to work. I have an multidimensional array and I wan´t iterate trough the array and check for a specific value. If the value equals a string then echo out a value of the array.

Here is the array and two values (the full array has a lot more):

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

I wan't to echo out the Full name of each user that is "Online". Here is what I'm using today but it's not working:

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

If I echo out $fullname and $status the correct data is printed out. But for some reason the IF statement is not working. If the user is Offline the echo is "No", but if the user is Online there is no echo at all.

EDIT - Solved
Updated the array keys with quotes and $data[...] as was suggested below. I found a typo that was causing a false output. Thanks for all the help.

  • 写回答

4条回答 默认 最新

  • dongmei2956 2012-11-11 21:29
    关注

    This is working okay for me :

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

    Go through foreach in php to know more details about foreach.

    Hope that helps. Happy coding.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看