如何在 foreach 中使用(或组合)多个数组

How to use (or combine) multiple arrays for use in a foreach

如果发帖者是用户组 5、6 或 7 的成员,我正尝试在 vbulletin 论坛上显示一些文本。过去,当我使用数组时,它们通常只有一个数组输出.我当前的代码有多个数组,我不确定如何使用。 usergroupid & membergroupids字段中存储的数据是基于组id的一个数字。

CentOS Linux 7.6.1810,phpmyadmin 4.8.4,服务器版本 5.5.60-MariaDB,PHP 7.1.29。 我试过 array_merge 但是因为值来自数据库,所以我不知道如何给每个数组一个键和值。我相信每个键 and/or 值必须是唯一的才能合并数组。

我的代码

$current_thread = $thread['threadid'];  

    $query = $vbulletin->db->query_first("  
        SELECT user.usergroupid, user.membergroupids  
        FROM " . TABLE_PREFIX . "thread AS thread  
        LEFT JOIN " . TABLE_PREFIX . "user AS user ON (user.userid = thread.postuserid)  
        WHERE thread.threadid = " . $current_thread . "  
        "); 

    $primary_group = $query['usergroupid'];  
    $secondary_groups = $query['membergroupids'];  

    if(!empty($secondary_groups)) {  
        $groups = $primary_group . "," . $secondary_groups;  
    } else {  
        $groups = $primary_group;  
    }      

    $data = explode(PHP_EOL, $groups); 

    foreach ($data AS $data_groups)  
    {
    $usergroup = array_map('trim', explode(',', $data_groups));  
    print("<pre>".print_r($usergroup,true)."</pre>");
    }

    vB_Template::preRegister('threadbit',array('group' => $groups_all));

输出

Array
(
    [0] => 6
)
Array
(
    [0] => 2
    [1] => 5
)
Array
(
    [0] => 6
)
Array
(
    [0] => 6
)
Array
(
    [0] => 2
    [1] => 5
)
Array
(
    [0] => 6
)
Array
(
    [0] => 6
)
Array
(
    [0] => 6
)
Array
(
    [0] => 2
    [1] => 5
)

以上输出基于正在查看的论坛中的 9 个主题。有没有一种方法可以检查线程启动器是否在用户组 5、6 或 7 中,然后我可以稍后使用?

您可以使用 array_intersect 检查数组值是否存在于 5,6,7

$result = [];
foreach ($data as $data_groups) {
    $usergroup = array_map('trim', explode(',', $data_groups));
    $temp      = array_intersect($usergroup, [5, 6, 7]); // checking if $usergroup 
                                                         //valus matches
    if (count($temp) > 0) {
        $result[] = $data_groups; 
        // if don't want complete data groups then
        //$result[] = $temp; // only matched groups will add
    }
}
// you can use $result for your requirement 

array_intersect — 计算数组的交集