【问题标题】:How to use (or combine) multiple arrays for use in a foreach如何在 foreach 中使用(或组合)多个数组
【发布时间】:2019-05-16 13:42:59
【问题描述】:

如果线程启动者是用户组 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 但因为值来自数据库,我不知道如何给每个数组一个键和值。我相信每个键和/或值必须是唯一的才能合并数组。

我的代码

$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 中,以便以后使用?

【问题讨论】:

    标签: php mysql arrays explode


    【解决方案1】:

    您可以使用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 — 计算数组的交集

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多