PHP 数组去重:如何去除 stdclass 对象中重复的 title 字段
PHP 数组去重:如何去除 stdclass 对象中重复的 title 字段
您有一个 PHP 数组,每个数组元素都是一个 stdclass 对象,结构如下:
{
"id": 1135523,
"title": "省考招警考试面试模拟题:背诗词'免费'得门票,取得多赢效果",
"exam_ids": "[41]",
"category_ids": "[33]",
"district_id": 100000,
"update_time": "2023/06/28 16:44:02",
"is_publish": 1,
"publish_time": "2023/06/28 16:43:15",
"url": "https://www.eoffcn.com/kszx/detail/1135523.html",
"kaoshiName": "招警"
}
您希望去除所有 title 字段重复的 stdclass 对象,保留其他内容。
解决方法:
您可以使用循环遍历数组的方式,通过比较每个 stdclass 的 title 字段来判断是否重复,然后将非重复的 stdclass 添加到一个新的数组中。
示例代码:
<?php
// 原始数组
$originalArray = [
(object) [
"id" => 1135523,
"title" => "省考招警考试面试模拟题:背诗词'免费'得门票,取得多赢效果",
"exam_ids" => "[41]",
"category_ids" => "[33]",
"district_id" => 100000,
"update_time" => "2023/06/28 16:44:02",
"is_publish" => 1,
"publish_time" => "2023/06/28 16:43:15",
"url" => "https://www.eoffcn.com/kszx/detail/1135523.html",
"kaoshiName" => "招警"
],
(object) [
"id" => 1135522,
"title" => "2024国考招警考试面试模拟题:推动生物多样性治理,共建地球生命共同体",
"exam_ids" => "[41]",
"category_ids" => "[33]",
"district_id" => 100000,
"update_time" => "2023/06/28 16:44:02",
"is_publish" => 1,
"publish_time" => "2023/06/28 16:43:06",
"url" => "https://www.eoffcn.com/kszx/detail/1135522.html",
"kaoshiName" => "招警"
]
];
// 用于存储非重复stdclass的新数组
$filteredArray = [];
// 用于存储已出现的title值
$titles = [];
foreach ($originalArray as $item) {
// 检查title字段是否已经存在
if (!in_array($item->title, $titles)) {
// 添加非重复的stdclass到新数组
$filteredArray[] = $item;
// 将title字段添加到已出现的title值数组中
$titles[] = $item->title;
}
}
// 打印结果
print_r($filteredArray);
?>
这样,$filteredArray 中将只包含没有重复 title 字段的 stdclass 对象。
代码说明:
- 原始数组
$originalArray:包含多个 stdclass 对象的数组。 - 过滤数组
$filteredArray:用于存储过滤后的非重复 stdclass 对象。 - title 数组
$titles:用于存储已经出现的 title 值,用于判断是否重复。 - 循环遍历:使用
foreach循环遍历$originalArray中的每个 stdclass 对象。 - 判断重复:使用
in_array函数判断当前 stdclass 对象的 title 是否在$titles数组中。 - 添加非重复对象:如果 title 不重复,则将该 stdclass 对象添加到
$filteredArray数组中,并将 title 值添加到$titles数组中。
通过上述代码,您可以成功地从原始数组中去除所有 title 重复的 stdclass 对象,并保留其他内容。
原文地址: https://www.cveoy.top/t/topic/o1E3 著作权归作者所有。请勿转载和采集!