problem in using in array function
Hi,
I am building a drop down menu of cities from an xml file.
Because the xml file contain duplication I used the function in array to make sure I don't echo twice the same value.
This is the code:
Code:
<?php
$DiurPlus=file_get_contents('http://www.diur-plus.co.il/xml.aspx');
$xmlDiurPlus=simplexml_load_string($DiurPlus);
$imagelist=$xmlDiurPlus;
echo "<select>";
$cities=array();
foreach ($xmlDiurPlus->propertyList as $propertylist){
if (!in_array($propertylist->city,$cities)){
echo '<option value="'.$propertylist->city.'">'.$propertylist->city.'</option>';
$cities[]=$propertylist->city;
}
}
echo "</select> ";
?>
Yet when I run it, I still get the same value more than once.
Where is my mistake?
Are there any CaSe differences or white spaces in the city fields?
Otherwise the code looks fine to me.
Originally Posted by
bionoid
Are there any CaSe differences or white spaces in the city fields?
Otherwise the code looks fine to me.
just an update.
The problem was the white space.
I solved it with this code:
PHP Code:
<?php
$DiurPlus = file_get_contents ( 'http://www.diur-plus.co.il/xml.aspx' );
$xmlDiurPlus = simplexml_load_string ( $DiurPlus );
$imagelist = $xmlDiurPlus ;
echo "<select>" ;
$cities []= "" ;
foreach ( $xmlDiurPlus -> propertyList as $propertylist ){
if (! in_array ( trim ( $propertylist -> city ), $cities )){
echo '<option value="' . $propertylist -> city . '">' . $propertylist -> city . '</option>' ;
$cities []= trim ( $propertylist -> city );
}
}
echo "</select> " ;
?>
Ignore my last comment.
My PHP array keys didn't seem to like utf8 characters. So I'm using MD5 (which I presume is multibyte safe) to generate unique keys:
PHP Code:
<?php
$DiurPlus = file_get_contents ( 'http://www.diur-plus.co.il/xml.aspx' );
$xmlDiurPlus = simplexml_load_string ( $DiurPlus );
$imagelist = $xmlDiurPlus ;
$cities = array();
echo '<select>' ;
foreach ( $xmlDiurPlus -> propertyList as $propertylist ) {if ( $propertylist -> city ) { $cities [ md5 ( $propertylist -> city )] = $propertylist -> city ;}}
foreach ( $cities as $city ) {echo '<option value="' . $city . '">' . $city . '</option>' ;}
echo '</select>' ;
?>
Hope that helps.
Beware, MD5's can be the same for two completely different inputs.
Originally Posted by
temp.user123
You know... You're not so smart. Do you need me to educate you?
If you say, "please," (and do so, nicely) then I will show you where you're dead wrong.
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks