Home > Backend Development > PHP Tutorial > [数组]请问错出在哪里了

[数组]请问错出在哪里了

WBOY
Release: 2016-06-23 13:37:25
Original
1142 people have browsed it

<?php$rc = array("07-12"=>"同学聚会", "07-21"=>"信用还贷", "07-23"=>"购买商品");$date = "07-23";foreach($rc as $key=>$value){if($key == $date){echo "<script>alert('".$key."日备忘:".$value."')</script>";break;}else{echo "<script>alert('无备忘')</script>";break;}}?>
Copy after login


第三行如果是:$date = "07-12", 弹出提示框:07-12日备忘:同学聚会
第三行如果是:$date = "07-21",或者是: $date = "07-23",应该同上类似,但是弹出提示框:无备忘
请问错出在哪里了?


回复讨论(解决方案)

你不是有break吗,遍历一次就退出了。

同楼上,第10行不能break

$rc = array("07-12"=>"同学聚会", "07-21"=>"信用还贷", "07-23"=>"购买商品");$date = "07-23";$msg = '';foreach($rc as $key=>$value){  if($key == $date){    $msg = "<script>alert('".$key."日备忘:".$value."')</script>";    break;  }}if(! $msg) $msg = "<script>alert('无备忘')</script>";echo $msg;
Copy after login
Copy after login
想想为什么

$rc = array("07-12"=>"同学聚会", "07-21"=>"信用还贷", "07-23"=>"购买商品");$date = "07-23";$msg = '';foreach($rc as $key=>$value){  if($key == $date){    $msg = "<script>alert('".$key."日备忘:".$value."')</script>";    break;  }}if(! $msg) $msg = "<script>alert('无备忘')</script>";echo $msg;
Copy after login
Copy after login
想想为什么

正解。谢谢楼上诸位。

可是为什么这样写,我还没想明白。

这样写明白吗?

$rc = array("07-12"=>"同学聚会", "07-21"=>"信用还贷", "07-23"=>"购买商品");$date = "07-23";$msg = "<script>alert('无备忘')</script>";//给个初值foreach($rc as $key=>$value){  if($key == $date){ //如果存在就修改    $msg = "<script>alert('".$key."日备忘:".$value."')</script>";    break;//只是为了提前结束循环  }}echo $msg;
Copy after login

xuzuning兄游刃有余,6楼的代码通俗易懂。
我用netbeans-xdebug运行了1楼的代码,单步查看变量值的变化,明白1楼代码的错误所在了。
1楼代码如果第三行是:$date = "07-21"; 第一次循环时,$key为07-12,不等于$date07-21,这时弹出js提示框是"无备忘", 而不是希望弹出的:“07-21日备忘:信用还贷”。
正确的方法应该是这时不弹出提示框,而是到$key==$date时才弹出提示框。
这种情况下一个循环里不能有两套echo。

很基础的问题,不注意的确会绕进去!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template