我正在使用Wordpress,而且我正在查询CPT。这是一个单个输出示例:
Array
(
[0] => WP_Post Object
(
[ID] => 1400
[post_author] => 1
[post_date] => 2017-10-20 14:43:48
[post_date_gmt] => 2017-10-20 13:43:48
[post_content] => content
[post_title] => test-case
[post_excerpt] => dsfsdfsd
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] =>
[post_name] => test-case
[to_ping] =>
[pinged] =>
[post_modified] => 2017-10-20 15:02:43
[post_modified_gmt] => 2017-10-20 14:02:43
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://example.com/site/?post_type=bulletin&p=1400
[menu_order] => 0
[post_type] => bulletin
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
)
我有很多具有相同标题的重复帖子,但是他们使用了post_meta
中包含的UID(此示例中未显示,因为它不相关)
我使用此代码遍历所有帖子,找到重复项并创建一个新数组,其中包含重复的帖子的单个实例。
foreach ($query->posts as $post) {
if (!array_key_exists($post->bid, $new_array)) {
$new_array[$post->bid] = $post;
}
}
问题:如何使用上面的循环另外计算每个帖子的重复项?
答案 0 :(得分:2)
如果您只需要计算它们,您可以这样做:
$duplicateCounts = array_count_values(array_map(function ($post) {
return $post->post_title;
},$query->posts);
foreach ($query->posts as $post) {
if (!array_key_exists($post->bid, $new_array)) {
$new_array[$post->bid] = $post;
$new_array[$post->bid]->duplicate_count = $duplicateCounts[$post->post_title];
}
}
它的作用是:
$query->posts
结果数组转换为仅post_title
值的数组。这是通过使用array_map
完成的,array_count_values
将根据函数的结果更改每个数组条目的结果(在这种情况下获取post_title
)并将结果返回到新数组中。< / LI>
test-case
次12次,那么频率数组中会有[ "test-case" => 12 ]
这样的条目。完成所有这些操作后,只需检查频率数组中找到标题的次数即可。
答案 1 :(得分:1)
你只需要在现有代码中输入一个计数器。这似乎是一个奇怪的问题,但我们都有那些“森林树木”的时刻,所以你走了:
$duplicates = 0;
foreach ($query->posts as $post) {
if (!array_key_exists($post->bid, $new_array)) {
$new_array[$post->bid] = $post;
}
else {
$duplicates++;
}
}