我有一个像这样的数组
$test = array("sumber"=>array("f1","f2"),"ukraina"=>array("f3","f4"),"0"=>array("f5","f6"));
foreach($test as $key => $value){
if($key=="sumber"){
$a='';
for($i=0;$i<count($value);$i++){
$a.=$value[$i].", ";
}
echo $key." has ".$a."<br/>";
}
}
我希望结果只有这样
sumber有f1,f2,
但结果是这样的
sumber有f1,f2,
0有f5,f6,
请帮我如何只显示关键“sumber”??? 感谢。
答案 0 :(得分:3)
在===
条件中使用三重条件if($key=="sumber")
:
$test = array("sumber"=>array("f1","f2"),"ukraina"=>array("f3","f4"),"0"=>array("f5","f6"));
foreach($test as $key => $value){
if($key==="sumber"){
$a='';
for($i=0;$i<count($value);$i++){
$a.=$value[$i].", ";
}
echo $key." has ".$a."<br/>";
}
}
否则当if()
为空/ 0时,也会完成key
条件。
答案 1 :(得分:2)
你可以简单地使用这段代码:
$test = array("sumber"=>array("f1","f2"),"ukraina"=>array("f3","f4"),"0"=>array("f5","f6"));
if(array_key_exists("sumber",$test) && !empty($test['sumber'])) {
echo "sumber has".implode(",",$test['sumber']);
}
答案 2 :(得分:1)
查看有关比较值的PHP手册: http://www.php.net...comparison.php
<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump(0 === "01"); // false <- what you need
?>
答案 3 :(得分:0)
只需参考该特定元素开始?
<?php
if (!empty($test["sumber"])) {
foreach ($test["sumber"] as $values) {
echo "sumber has " . implode(", ", $values) . "<br />";
}
}
?>