Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从阵列中删除重复项_Php - Fatal编程技术网

Php 从阵列中删除重复项

Php 从阵列中删除重复项,php,Php,嗨,我有一个使用此函数从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

嗨,我有一个使用此函数从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;

}
创建后如何停止获取重复值或从数组中删除?

您只需稍后调用:

$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;
    }
}
但是,如果您的姓名不具有字符串可比性,则需要另一种方法。


为什么要制作二维数组?您只需执行
$return[]=$location->$field\u选择即可。感谢Gumbo,由于所有名为“Name”的索引,此方法似乎不起作用。尝试比较值,但作为对象和指针,即使值相同,它们也不同!感谢Brandon,这不起作用,因为所有索引都称为“Name”,所以array_unique只返回第一个元素。
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);