2013-02-11 72 views
0

我遇到图像问题。PHP处理重复元素

我尝试添加一个图像ID,当用户点击图像和id将被保存到数据库。

当页面重新加载时,具有id属性的图像将在img标签中显示id。

我标识具有id属性的图像的方式基于图像src。 但是,我发现有很多重复的图像,我的代码会将所有重复图像的id属性添加到 。

我只希望添加用户点击的图像的id属性。

我的代码

this.id是图像的新的id属性,它从数据库中产生。

//click image codes.... 
//assign the id to the clicked image (not all duplicated images) 
this.img.attr('id',this.id); 

时重新加载页面...

$doc = new DOMDocument(); 
$doc->loadHTML($myHtml); 

      $imageTags = $doc->getElementsByTagName('img'); 

      //get the images that has id attribute from DB 
      $imgSource=$this->imgSource; //imgSource is an array 
      $imgID=$this->imgID;   //imgID is an array 

      //search the htmlstring and add the id attribute to the images 
      foreach($imageTags as $tag) { 
      $source=$tag->getAttribute('src'); 

      //if the html contains the image that has id attribute.. 
       if(in_array($source, $imgSource)){ 

       $ids=array_keys($imgSource,$source); 
       foreach($ids as $id){ 
        $tag->setAttribute('id',$imgID[$id]); 
        $myHtml=$doc->saveHTML(); 
       } 
       } 
      } 
      } 

我上面的代码将ID分配到已经存储在数据库ID图像。但是,它也会将 分配给所有重复的图像。我需要区分这些重复的图像,我只能在我的情况下使用php。这个问题让我疯狂!如果有人能帮助我,我将不胜感激。非常感谢。

回答

1

如果问题是要区分重复,那么避免它们的适当部分是更改代码添加到重复图像的代码,不是吗?

我不完全理解的PHP代码如何发布与IDS的作品,但我想$this->imgSource$this->imgID是这样的:

$this->imgSource = array(
    [0] => 'src/image/a', 
    [1] => 'src/image/b', 
    [2] => 'src/image/c', 
    [3] => 'src/image/a' 
); 
$this->imgID = array(
    [0] => 111, 
    [1] => 222, 
    [2] => 333, 
    [3] => 444 
); 

所以当$source'src/image/a'它会做这样的事情:

$tag->setAttribute('id', 111); 
$tag->setAttribute('id', 444); 

如果这是你想要避免的,我建议删除id值以防止再次使用它。

$ids = array_keys($imgSource, $source); 
foreach($ids as $id) { 
    if(isset($imgID[$id])) { 
     $tag->setAttribute('id', $imgID[$id]); 
     $myHtml = $doc->saveHTML(); 
     unset($imgID[$id]); 
     break; 
    } 
} 
+0

非常感谢你一个Rodas。你很明白我的问题。我很感激。只有当用户点击第一张重复的图像时,取消设置才有效。如果用户单击第二或第三张图像,则不会为其分配标识,因为代码找到了第一张图像的图像来源。 +1 – FlyingCat 2013-02-12 00:25:45

+0

然后,只有当用户点击一个没有重复的图像时,它才会起作用吗?我想我可能在这句话中错过了一些东西:“它不会将id分配给他们,因为代码找到了第一张图片的图片来源。” – 2013-02-12 00:46:49

+0

是的,它只适用于图像不重复的情况。我的错。 – FlyingCat 2013-02-12 01:06:34