编辑:浏览器正在输出和解释字符串。愚蠢的错误。
在我的项目中,我创建了一个类来生成我需要的 HTML 标签,而不是我自己将它们全部回显。我有一个在名为generateTag($control, $isCardValue = true)
.php 的 php 类中调用的函数Card
。此函数根据通过数组参数传递的属性生成 HTML 标记$control
。这是函数的样子:
public function generateTag($control, $isCardValue = true) {
if ($isCardValue) {
// First we convert the 'class' element to an array
if (isset($control['class']) && gettype($control['class']) !== 'array') {
$control['class'] = array($control['class']);
}
// Then we add the 'card-value' class to that array.
$control['class'][] = 'card-value';
}
// The tag key is mandatory
$tag = '<' . $control['tag'];
// All keys other than 'tag' & 'content' are considered attributes for the HTML tag.
foreach ($control as $key => $value) {
switch ($key) {
case 'tag':
break;
case 'content':
break;
default:
if (gettype($value) === 'array') {
$tag .= ' ' . $key . '="' . implode(' ', $value) . '"';
} elseif (gettype($value) === 'NULL') {
$tag .= ' ' . $key;
} else {
$tag .= ' ' . $key . '="' . $value . '"';
}
break;
}
}
$tag .= '>';
// If the 'content' key is not passed through $control, we assume that the tag
// doesn't need to be closed (e.g. <input> doesn't need a closing tag)
if (isset($control['content'])) {
if (gettype($control['content']) === 'array') {
foreach ($control['content'] as $child) {
$tag .= $this->generateTag($child);
}
} else {
$tag .= $control['content'];
}
$tag .= '</' . $control['tag'] . '>';
}
return $tag;
}
我使用这个函数来创建一个盒子的所有<option>
标签。<select>
我只是循环遍历一个数组来生成标签:
foreach ($lists['tags'] as $key => $tag) {
$tag_options[$key] = array(
'tag' => 'option',
'value' => $tag['tag_id'],
'content' => $tag['tag_name_en'],
);
var_dump($card->generateTag($tag_options[$key], false));
}
这就是事情变得奇怪的地方。我在生成的字符串上调用 var_dump,得到以下输出:
string(32) "" string(35) "" string(33) "" string(33) "" string(38) "" string(32) "" string(42) "" string(30) "" string(41) "" string(34) "" string(35) "" string(34) "" string(29) "" string(36) "" string(37) "" string(31) "" string(36) "" string(67) "" string(36) "" string(33) "" string(36) "" string(36) ""
似乎它正在创建一个长度约为 35 的空字符串?最奇怪的是,当我调用 a 时substr($tag_options[$key], 0, 1)
,它给了我<
应有的信息。但是当我打电话时substr($tag_options[$key], 0, 2)
,它给了我长度为 2 的“空”字符串。关于发生了什么的任何见解?