_array()中的PHP无法正常工作
我在下面有一个_array()中的PHP无法正常工作,php,arrays,if-statement,Php,Arrays,If Statement,我在下面有一个if语句,它检查数组中是否存在值,如果不存在,则将其添加到数组中。 显然,即使该值在数组中,它也会再次触发它 据我所知,它应该只显示每个值的1,因为它只会触发3次,如下所示: Digital Photography -> 0 Step by Step Macintosh Training -> 0 How to become a Powerful Speaker -> 0 if (!isset($courseList[$unit['course_name']])
if
语句,它检查数组中是否存在值,如果不存在,则将其添加到数组中。
显然,即使该值在数组中,它也会再次触发它
据我所知,它应该只显示每个值的1,因为它只会触发3次,如下所示:
Digital Photography -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
if (!isset($courseList[$unit['course_name']])) {
守则:
if (!in_array($unit['course_name'], $courseList)) {
$courseList[$unit['course_name']]['name'] = $unit['course_name'];
$courseList[$unit['course_name']]['seconds'] = 0;
echo $courseList[$unit['course_name']]['name'] . ' -> ' . $courseList[$unit['course_name']]['seconds'];
echo "<BR>";
}
这是变量转储($unit)
:
谢谢你的帮助 在数组中()
方法检查数组值,而不是键。从您的示例中,我可以看到,作为值,您有一个带有name
和seconds
字段的数组。
我想您需要检查数组中是否存在该id
所以这如果:
if (!in_array($unit['course_name'], $courseList)) {
应该这样改变:
Digital Photography -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
if (!isset($courseList[$unit['course_name']])) {
这样可以检查$unit['course\u name']
是否作为键在数组中。在数组中()
方法检查数组值,而不是键。从您的示例中,我可以看到,作为值,您有一个带有name
和seconds
字段的数组。
我想您需要检查数组中是否存在该id
所以这如果:
if (!in_array($unit['course_name'], $courseList)) {
应该这样改变:
Digital Photography -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
if (!isset($courseList[$unit['course_name']])) {
通过这种方式,您可以检查$unit['course\u name']
是否在数组中作为键。如果数组中只有值,则应在数组中使用函数,如下示例所示:
$array = array("A", "B", "C");
in_array($string, $array) ? "found" : "not found";
$array = array("A" => "Result A", "B" => "Result B", "C" => "Result C");
isset($array[$string]) ? "found" : "not found";
否则,如果您有一个带有键的数组,则应使用isset
函数,如下例所示:
$array = array("A", "B", "C");
in_array($string, $array) ? "found" : "not found";
$array = array("A" => "Result A", "B" => "Result B", "C" => "Result C");
isset($array[$string]) ? "found" : "not found";
如果数组中只有值,则应在数组中使用函数,如下例所示:
$array = array("A", "B", "C");
in_array($string, $array) ? "found" : "not found";
$array = array("A" => "Result A", "B" => "Result B", "C" => "Result C");
isset($array[$string]) ? "found" : "not found";
否则,如果您有一个带有键的数组,则应使用isset
函数,如下例所示:
$array = array("A", "B", "C");
in_array($string, $array) ? "found" : "not found";
$array = array("A" => "Result A", "B" => "Result B", "C" => "Result C");
isset($array[$string]) ? "found" : "not found";
$courseList
最初分配在何处/如何分配?$courseList=array()代码>在循环之外。最初分配$courseList的位置/方式是什么?$courseList=array()代码>在循环之外。那太完美了!它回答了我的问题,教了我更多的PHP!干杯,伙计!太完美了!它回答了我的问题,教了我更多的PHP!干杯,伙计!