【问题标题】:Counting Duplicate Values In Multidimension Array of Objects计算多维对象数组中的重复值
【发布时间】:2019-06-03 15:06:58
【问题描述】:

我有一个多维数组对象 $all2[$i][$j] 未定义但通过我的 laravel sql 查询请求收到:

for($i=0; $i<(count($all));$i++){
            $uID = HashtagFollow::select('user_id')->where('hashtag_id', $all[$i]->hashtag_id)->where('user_id', '!=', $loggedin->id)->get();

    for($j=0;$j<count($uID);$j++){
$all2[$i][$j] = HashtagFollow::select('hashtag_id')->where('user_id', $uID[$j]->user_id)->whereNotIn('hashtag_id', $all)->orderBy('hashtag_id')->get();
}
}

给出以下输出:

0: [[{hashtag_id: 5}], [{hashtag_id: 5}, {hashtag_id: 13}], [{hashtag_id: 2}, {hashtag_id: 13}]]
    0: [{hashtag_id: 5}]
    1: [{hashtag_id: 5}, {hashtag_id: 13}]
    2: [{hashtag_id: 2}, {hashtag_id: 13}]

1: [[{hashtag_id: 5}, {hashtag_id: 13}], [{hashtag_id: 5}], [{hashtag_id: 5}],…]
    0: [{hashtag_id: 5}, {hashtag_id: 13}]
    1: [{hashtag_id: 5}]
    2: [{hashtag_id: 5}]
    3: [{hashtag_id: 12}, {hashtag_id: 13}]

2: [[{hashtag_id: 5}, {hashtag_id: 13}], [{hashtag_id: 5}], [{hashtag_id: 12}, {hashtag_id: 13}]]
    0: [{hashtag_id: 5}, {hashtag_id: 13}]
    1: [{hashtag_id: 5}]
    2: [{hashtag_id: 12}, {hashtag_id: 13}]

3: [[{hashtag_id: 5}, {hashtag_id: 13}], [{hashtag_id: 2}, {hashtag_id: 12}, {hashtag_id: 13}],…]
    0: [{hashtag_id: 5}, {hashtag_id: 13}]
    1: [{hashtag_id: 2}, {hashtag_id: 12}, {hashtag_id: 13}]
    2: [{hashtag_id: 5}]
    3: [{hashtag_id: 5}, {hashtag_id: 13}]
    4: [{hashtag_id: 2}, {hashtag_id: 13}]
    5: [{hashtag_id: 12}, {hashtag_id: 13}]

4: [[{hashtag_id: 5}, {hashtag_id: 13}], [{hashtag_id: 5}], [{hashtag_id: 5}],…]
    0: [{hashtag_id: 5}, {hashtag_id: 13}]
    1: [{hashtag_id: 5}]
    2: [{hashtag_id: 5}]
    3: [{hashtag_id: 5}, {hashtag_id: 13}]
    4: [{hashtag_id: 12}, {hashtag_id: 13}]

5: [[{hashtag_id: 5}], [{hashtag_id: 2}, {hashtag_id: 12}, {hashtag_id: 13}],…]
    0: [{hashtag_id: 5}]
    1: [{hashtag_id: 2}, {hashtag_id: 12}, {hashtag_id: 13}]
    2: [{hashtag_id: 5}, {hashtag_id: 12}, {hashtag_id: 13}]
    3: [{hashtag_id: 5}]
    4: [{hashtag_id: 2}, {hashtag_id: 13}]
    5: [{hashtag_id: 12}, {hashtag_id: 13}]

我现在正在尝试循环这个对象数组并计算每个 hashtag_id 有多少。

预期输出: hashtag_id:2 计数:2 hashtag_id:5 计数:5 hashtag_id:12 计数:3 hashtag_id:13 计数:6

【问题讨论】:

  • 您如何获得这些预期计数?对于 hashtag_id:2,有 3 个组包含该 hashtag_id,所有组共有 5 个。你从哪里得到计数:2?
  • 你到底要数什么?
  • @newUserName02 他们来自我的数据库,我的 sql 查询是一个循环。它遍历我的数组 $uID 中的每个用户,并给我他们的 hashtag_ids。和 count: 2 是我想要返回的我希望它读取我的维度数组 $all2 并告诉我每个 hashtag_id: 2, 5, 12, 13 有多少存在于新数组中,并给我一个计数.
  • 我知道他们的期望值是多少,因为我已经把它们加起来了,所以我知道会发生什么@newUserName02

标签: php laravel multidimensional-array eloquent duplicates


【解决方案1】:

您可能需要考虑直接查询这些计数。

例如

SELECT hashtag_id, user_id, COUNT(*) AS count FROM HashtagFollow GROUP BY hashtag_id, user_id;

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2021-12-10
    • 2022-01-12
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2021-07-06
    相关资源
    最近更新 更多