Remove duplicates from Array

前端 未结 2 1046
粉色の甜心
粉色の甜心 2021-01-22 09:58

Hi I have an array created from an XML file using this function.

# LOCATIONS XML HANDLER
#creates array holding values of field selected from XML string $xml
# @         


        
相关标签:
2条回答
  • 2021-01-22 10:45

    http://php.net/manual/en/function.array-unique.php

    $input = array(4, "4", "3", 4, 3, "3");
    $result = array_unique($input);
    var_dump($result);
    
    0 讨论(0)
  • 2021-01-22 10:49

    You could simply call array_unique afterwards:

    $return = array_unique($return);
    

    But note:

    Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

    Or, instead of removing duplicates, you could use an additional array for the names and use the uniqueness of PHP’s array keys to avoid duplicates in the first place:

    $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;
        }
    }
    

    But if your names are not string-comparable, you would need a different approach.

    0 讨论(0)
提交回复
热议问题