您好我使用此函数从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 :(得分: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;
}
}
但如果你的名字不具有字符串可比性,那么你需要采用不同的方法。
答案 1 :(得分:1)
http://php.net/manual/en/function.array-unique.php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);