我有这样的数组:
Array
(
[0] => stdClass Object
(
[model_id] => 1
[category_id] => 1
[model_name] => Xperia
[category_name] => Mobile
[category_image] => 81649e37620644bec47244fda5233363.jpg
[item_type] => 1
)
[1] => stdClass Object
(
[model_id] => 3
[category_id] => 1
[model_name] => HTC One
[category_name] => Mobile
[category_image] => 250a3e4655454feaec8e2537d149846a.jpg
[item_type] => 1
)
[2] => stdClass Object
(
[model_id] => 9
[category_id] => 3
[model_name] => Apple TV
[category_name] => Televisions
[category_image] => no_image.jpg
[item_type] => 1
)
[3] => stdClass Object
(
[model_id] => 4
[category_id] => 2
[model_name] => MacBook
[category_name] => Laptop
[category_image] => c9890535d26bd06189fc22940a5ee5da.jpg
[item_type] => 1
)
[4] => stdClass Object
(
[model_id] => 2
[category_id] => 1
[model_name] => iPhone 7
[category_name] => Mobile
[category_image] => cab0631b071d0562412ccab2279d391e.jpg
[item_type] => 1
)
[5] => stdClass Object
(
[model_id] => 5
[category_id] => 3
[model_name] => Samsung TV
[category_name] => Televisions
[category_image] => e60bd4822e516a93f1e99a8b456b70ce.jpg
[item_type] => 1
)
)
如何删除category_id
以及item_type
重复的元素?使用下面的代码,我只能删除任何单个值重复的元素。
foreach($all_device_categories as $arr){
if(!isset($result[$arr->category_id])){
$result[$arr->category_id] = $arr;
}
}
更新:category_id
以及item_type
不应同时重复。如果category_id
重复但不重复item_type
,反之亦然。
答案 0 :(得分:2)
用于多键匹配。您可以将这些键组合到数组键中。试试这个:
foreach($all_device_categories as $arr){
if(!isset($result[$arr->category_id.$arr->item_type])){
$result[$arr->category_id.$arr->item_type] = $arr;
}
}
答案 1 :(得分:2)
如果category_id
和item_type
重复,您只需要存储一个值,那么您需要使用其他字符连接它们,例如: - 。如果你不这样做,那么一些信息将被遗漏。
foreach($all_device_categories as $arr){
$result[$arr->category_id.'-'.$arr->item_type] = $arr;
}
我认为这会对您有所帮助。如果发现任何匹配,这将始终采用更新数组值。如果您不想获取更新值,那么只需在存储新数组之前应用条件。
foreach($all_device_categories as $arr){
if(!isset($result[$arr->category_id.'-'.$arr->item_type])){
$result[$arr->category_id.'-'.$arr->item_type] = $arr;
}
}
第二个例子只存储第一个匹配,如果重复出现则会避免。