我有一个具有'category'属性的对象数组。我需要得到不同类别的列表,如果我有方法从对象中获得类别,我该怎么做呢?下面所示创建了数组中所有类别的列表,但显然有许多重复的类别:
foreach (getSourceCodes() as $source) {
echo $source->getCategory();
}
您可以在php中使用array_unique()
$categories = array();
foreach (getSourceCodes() as $source) {
array_push($categories, $source->getCategory());
}
$categories = array_unique($categories);
如果categories是多维的,则使用此方法序列化它,然后获得唯一数组,然后将其更改回数组。
$categories = array_map("unserialize", array_unique(array_map("serialize", $categories)));
如果使用类别作为数组键,则根据定义它将是唯一的。
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));
不确定您的列表是什么格式,但假设逗号分隔值…
$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);