【发布时间】:2023-01-20 19:38:44
【问题描述】:
我的目标:用 while 循环中的值填充一个数组。在将它们添加到数组之前,我想检查它们是否存在。结构应如下所示:
Array
(
[0] => Array
(
[0] => "<p>text</p>"
[1] => "<p>more</p>"
[2] => "<p>thing</p>"
)
[1] => Array
(
[0] => "<p>text</p>"
[1] => "<p>more</p>"
[2] => "<p>thing</p>"
)
)
这像这样工作:
$i = 1;
$content = array();
$output = array();
while ($i <= 2) :
$text = '"<p>text</p>"';
$more = '"<p>more</p>"';
$some = '"<p>thing</p>"';
$content[] = [$text, $more, $some];
$i++;
endwhile;
$output[] = array(
'content' => $content
);
print_r($content);
但是如果我尝试检查一个值是否存在并将其添加到数组中
$i = 1;
$content = array();
$output = array();
while ($i <= 2) : $i++;
$text = '"<p>text</p>"';
$more = '"<p>more</p>"';
$some = '"<p>thing</p>"';
if ($text) :
$content[] = [$text];
elseif ($more) :
$content[] = [$more];
elseif ($some) :
$content[] = [$some];
endif;
endwhile;
$output[] = array(
'content' => $content
);
print_r($content);
我只得到第一个附加值
Array
(
[0] => Array
(
[0] => "<p>text</p>"
)
[1] => Array
(
[0] => "<p>text</p>"
)
)
【问题讨论】:
-
改变否则只是如果
-
$text已设置,因此无需执行elseifs。当您在之前的行中明确定义它们时,为什么还要进行检查? -
你在这里是什么意思,检查它们是否存在?
if ($text)对于您显示的代码将始终为真,因为您之前分配了$text = '"<p>text</p>"';,并且该值是真实的。
标签: php arrays while-loop