我有一个带有'类别的对象数组'属性。我需要得到一个不同类别的列表,我怎么能这样做,因为我有一个方法从对象中获取类别?下面显示的是创建数组中所有类别的列表,但显然有很多重复的类别:
foreach (getSourceCodes() as $source) {
echo $source->getCategory();
}
答案 0 :(得分:4)
您可以在php中使用array_unique()
。
$categories = array();
foreach (getSourceCodes() as $source) {
array_push($categories, $source->getCategory());
}
$categories = array_unique($categories);
如果类别是多维的,那么使用此方法将其序列化,然后获取唯一数组,然后将其更改回数组。
$categories = array_map("unserialize", array_unique(array_map("serialize", $categories)));
答案 1 :(得分:1)
如果您将类别用作数组键,则根据定义它将是唯一的。
foreach (getSourceCodes() as $source) {
// The value is irrelevant. You can use a counter if you want to keep track of that.
$an_array[$source->getCategory()] = true;
// The key is just overwritten for duplicate values of getCategory()
}
// Then you can use array_keys to get the keys as values.
var_dump(array_keys($an_array));
答案 2 :(得分:0)
不确定列表的格式是什么,但假设使用逗号分隔值...
$aCategories = array();
$aList = array();
foreach (getSourceCodes() as $source) {
// Get categories as comma separated string list???
$sList = $source->getCategory();
// Convert string list to array
$aTmpList = explode(",",$sList);
//Check temp list against current list for new categories
$aDiffList = array_diff($aList,$atmpList);
//Merge new categories into current list
$aList = array_merge($aDiffList,$aList);
}
// Convert array to string list
$sCategories = implode(",", $aList);