Reputation: 14260
I am trying to set id attribute to some of the images that are returning from DB
The id attribute only apply to the images that the user clicks.
my problem is that I have duplicated images and it's hard to distinquish the different.
I store the clicked image src
into DB to identify which image should have id attribute.
The id will automatically generated whne user clicks the images.
My html is like
<div>
<img src='test1.jpg'/>
<img src='test1.jpg'/>
<img src='test1.jpg'/>
<img src='test2.jpg'/>
<img src='test3.jpg'/>
</div>
to render the images in php
$html is the string that are returning from DB. it has all kind of html tags.
$doc = new DOMDocument();
@$doc->loadHTML($html);
$imageTags = $doc->getElementsByTagName('img');
$imgSource is the array of images that are supposed to have id attribute
$imgID is the array of ids for the images that were clicked
$source is the current image taht are being checked
foreach($imageTags as $tag) {
$source=$tag->getAttribute('src');
if(in_array($source, $imgSource)){
$ids=array_keys($imgSource,$source);
foreach($ids as $id){
$tag->setAttribute('id',$imgID[$id]);
$htmlString=$doc->saveHTML();
}
}
}
My code above will generate html like below if user clicks test1
and test2
images
<div>
<img id='123' src='test1.jpg'/>
<img id='123' src='test1.jpg'/>
<img id='123' src='test1.jpg'/>
<img id='456' src='test2.jpg'/>
<img src='test3.jpg'/>
</div>
id
123 applies to all test1.jpg
and it's not what I want.
I have tried to avoid this issue by finding image postion index.
so if the user clicks the second test1.jpg
, the index will be 2.
if the user clciks the third test1.jpg
, the index will be 3.
However, I am not sure how to apply that to my php codes. I can only change codes in php at the time. Can anyone help me about it? Thanks so much!
Upvotes: 0
Views: 91
Reputation: 15922
Not tested, but that's the idea:
$counter = array();
foreach($imageTags as $tag) {
$source=$tag->getAttribute('src');
if(in_array($source, $imgSource)){
$ids=array_keys($imgSource,$source);
foreach($ids as $id){
$counter[$imgID[$id]] = isset($counter[$imgID[$id]]) $counter[$imgID[$id]] + 1 : 0;
$tag->setAttribute('id',$imgID[$id] . '-' . $counter[$imgID[$id]]);
$htmlString=$doc->saveHTML();
}
}
You'll get ids like:
<div>
<img id='123.0' src='test1.jpg'/>
<img id='123-1' src='test1.jpg'/>
<img id='123-2' src='test1.jpg'/>
<img id='456-0' src='test2.jpg'/>
</div>
Upvotes: 1