我有以下PHP。
最终,我希望执行结束时的输出为:
Size1Size3
$footballTypes = "1,3";
$footballTypeNames = "";
foreach ( $footballTypes as $data ) {
switch ($data) {
case 1:
$footballTypeNames .= "Size 1";
case 2:
$footballTypeNames .= "Size 2";
case 3:
$footballTypeNames .= "Size 3";
}
}
echo $footballTypeNames;
但是,现在,我得到了错误:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\football.php on line 7
我哪里出错了?
答案 0 :(得分:4)
使用explode伴侣,
$footballTypes = explode(",", "1,3"); // here I explode
$footballTypeNames = "";
foreach ($footballTypes as $data) {
switch ($data) {
case 1:
$footballTypeNames .= "Size 1";break;
case 2:
$footballTypeNames .= "Size 2";break;
case 3:
$footballTypeNames .= "Size 3";break;
}
}
echo $footballTypeNames;
Demo。
如果可以的话,有多种方法可以实现这一目标,
1。
$footballTypes = explode(",", "1,3"); // here I explode
$temp = implode("",array_map(function($value){
return "Size $value";
}, $footballTypes));
print_r($temp);
答案 1 :(得分:3)
您不需要切换,因为您添加的文本仅为Size
。使用爆炸和内爆..
implode()函数从数组的元素中返回一个字符串。 语法:内爆(分隔符,数组)
explode()函数将字符串分成数组。 语法:爆炸(分隔符,字符串,限制)
$footballTypes = "1,2,3";
$footballTypeNames = implode('Size ', explode(',',$footballTypes));
echo 'Size '.$footballTypeNames;