如何解决PHP:foreach循环太多了
| 如果输入以下内容,则get_tag_id将带回第一个数组项目两次: 质地,客户 我得到这个回报: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));
}
}
get_tag_id()代码:
function get_tag_id($tag)
{
// Load Database
$this->load->database();
// Query Database
$this->db->where_in(\'Title\',$tag);
$query = $this->db->get(\'Tag\',1);
$result = $query->result();
// Return ID of Tag
//return $result[0]->TagID;
print_r($result);
}
解决方法
这是因为此代码在这里:
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,它将不再打印第一个数组两次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。