2011-06-04 152 views
2

您好我有一个使用此函数从XML文件创建的数组。删除数组中的重复项

# LOCATIONS XML HANDLER 
#creates array holding values of field selected from XML string $xml 
# @param string $xml 
# @parm string $field_selection 
# return array 
# 
function locations_xml_handler($xml,$field_selection){ 

    # Init return array 
    $return = array(); 
    # Load XML file into SimpleXML object 
    $xml_obj = simplexml_load_string($xml); 
    # Loop through each location and add data 

    foreach($xml_obj->LocationsData[0]->Location as $location){ 
    $return[] = array("Name" =>$location ->$field_selection,); 
    } 
    # Return array of locations 

    return $return; 

} 

我该如何停止获取重复值或从数组中删除一旦创建?

+0

为什么你做一个二维数组?你可以做'$ return [] = $ location - > $ field_selection'。 – Midas 2011-06-04 17:01:48

回答

3

你可以简单地调用之后array_unique

$return = array_unique($return); 

但要注意:

注意:有两个因素被认为是平等的,当且仅当(string) $elem1 === (string) $elem2。用词表示:当字符串表示是相同的。第一个元素将被使用。

或者,而不是删除重复,你可以使用名称的附加阵列,并使用PHP的数组键的唯一性,以避免在首位重复:

$index = array(); 
foreach ($xml_obj->LocationsData[0]->Location as $location) { 
    if (!array_key_exists($location->$field_selection, $index)) { 
     $return[] = array("Name" => $location->$field_selection,); 
     $index[$location->$field_selection] = true; 
    } 
} 

但如果你的名字是不是字符串可比较的,你需要一种不同的方法。

+0

非常感谢Gumbo,由于所有名为“Name”的索引似乎都不起作用。试过比较这些值,但是作为对象和指针,即使值相同,它们也是不同的! – WallyJohn 2011-06-06 10:59:12