PHP:foreach循环次数过多
如果输入以下内容,则get_tag_id将两次返回第一个数组项: 纹理,客户端 我得到这份报税表:PHP:foreach循环次数过多,php,loops,foreach,Php,Loops,Foreach,如果输入以下内容,则get_tag_id将两次返回第一个数组项: 纹理,客户端 我得到这份报税表: Array ( [0] => texture [1] => clients ) Array ( [0] => stdClass Object ( [TagID] => 4 [Title] => texture ) ) Array ( [0] => s
Array
(
[0] => texture
[1] => clients
)
Array
(
[0] => stdClass Object
(
[TagID] => 4
[Title] => texture
)
)
Array
(
[0] => stdClass Object
(
[TagID] => 4
[Title] => texture
)
)
Array
(
[0] => stdClass Object
(
[TagID] => 1
[Title] => clients
)
)
Array
(
[0] => texture
[1] => clients
)
代码如下:
// Break up Tags and Store in an Array
$delimiter = " ";
$tags = explode($delimiter, $this->input->post('tags'));
// Remove Accidential Spaces if any.
$tags = array_filter($tags, function($var){
return preg_match('/^[a-z-]+$/i', $var);
});
// Create Arrays for Seperation
$newTags = array();
$currentTags = array();
print_r($tags);
// Check if Tags Exists
foreach ($tags as $tag)
{
if (!$this->Bookmark_model->tag_exists($tag))
{
array_push($currentTags, strtolower($tag));
// Get ID of tags that are existing
foreach ($currentTags as $tagname)
{
$id = $this->Bookmark_model->get_tag_id($tagname);
echo $id;
}
}
else
{
array_push($newTags, strtolower($tag));
}
}
获取标签id()代码:
这是因为这里的代码:
array_push($currentTags, strtolower($tag));
// Get ID of tags that are existing
foreach ($currentTags as $tagname)
{
$id = $this->Bookmark_model->get_tag_id($tagname);
echo $id;
}
移除foreach,它将不再打印第一个数组两次
array_push($currentTags, strtolower($tag));
// Get ID of tags that are existing
foreach ($currentTags as $tagname)
{
$id = $this->Bookmark_model->get_tag_id($tagname);
echo $id;
}