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

标签 php mysql arrays explode

如果线程启动者是用户组 5、6 或 7 的成员,我会尝试在 vbulletin 论坛上显示一些文本。过去,当我使用数组时,它们通常只输出一个数组。我当前的代码有多个数组,我不知道如何使用。 usergroupidmembergroupids 字段中存储的数据是基于组 ID 的一个数字。

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

我的代码

$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 — 计算数组的交集

关于php - 如何在 foreach 中使用(或组合)多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56170023/

相关文章:

php - mysql inner join语句和内存过度使用!

php - 如何在 wordpress 中为每个自定义帖子类型设置不同的缩略图大小?

mysql - 创建用户、类型和类型标题表之间的关系

javascript - jQuery 根据用户输入从数组中获取值

Javascript 数组方法查找超过第一个值的 indexOf

Javascript-向数组字符串添加换行符

java - Web框架性能比较

php - 使用 PhpSpreadsheet 在 PHP 中读取 XLS

sql - JOIN 如何在数据库中工作的内部结构(SQL,比如在 MySQL 中)

mysql - 如何从一个表中选择与具有谓词的第二个表中的所有行相匹配的行?