好的,我要更新我的答案。我在 foreach 的末尾放置了 if 语句,它会为不存在的元素重复一个元素。我有两个原始的 if 语句,所以我将最后的 if 语句移到了它们基本上代表的 if 语句中,并且它起作用了。
这是第一个代码示例:
<?php
$row = $response;
$count = count($row);
for($i=0;$i<=$count-1;$i++){
@$type = $row[$i]['Type'];
if ($type == 'something') {
$someproduct = $row[$i]['someproduct'];
$somecolor = $row[$i]['somecolor'];
$length = $row[$i]['Length'];
if ($type == 'this') {
$img = 'myimage';
$this = $img . '<div id="somediv"><br /><strong>' . $someproduct . 'somecolor: ' . $somecolor . '<input type="button" value="value" onclick="somefunction(' . $i . ')" />' . '</div></div></li>';
}
if ($type == 'that') {
$img = 'myimage';
$that = $img . '<div id="somediv"><br /><strong>' . $someproduct . 'somecolor: ' . $somecolor . '<input type="button" value="value" onclick="somefunction(' . $i . ')" />' . '</div></div></li>';
}
if (!isset($whatever) || $whatever == 'that') {
echo $that;
}
if (!isset($whatever) || $whatever == 'this') {
echo $this;
}
}
}
?>
这是变化。我在这个项目上工作了很长时间,我忽略了我应该知道的小东西。
<?php
$row = $response;
$count = count($row);
for($i=0;$i<=$count-1;$i++){
@$type = $row[$i]['Type'];
if ($type == 'something') {
$someproduct = $row[$i]['someproduct'];
$somecolor = $row[$i]['somecolor'];
$length = $row[$i]['Length'];
if ($type == 'this') {
$img = 'myimage';
$this = $img . '<div id="somediv"><br /><strong>' . $someproduct . 'somecolor: ' . $somecolor . '<input type="button" value="value" onclick="somefunction(' . $i . ')" />' . '</div></div></li>';
if (!isset($whatever) || $whatever == 'this') {
echo $this;
}
}
if ($type == 'that') {
$img = 'myimage';
$that = $img . '<div id="somediv"><br /><strong>' . $someproduct . 'somecolor: ' . $somecolor . '<input type="button" value="value" onclick="somefunction(' . $i . ')" />' . '</div></div></li>';
if (!isset($whatever) || $whatever == 'that') {
echo $that;
}
}
}
}
?>
感谢您的建议和帮助