开发者

Manipulating Multi Dimensional array and representation

开发者 https://www.devze.com 2023-03-19 13:32 出处:网络
I want to find out which user is not part of other games available in databasei get an array as following

I want to find out which user is not part of other games available in database i get an array as following

$arr2=Array
(
    (0) => Array
        (
            (uid) => 1,
            (game_id) => 22
        ),

    (1) => Array
        (

            (uid) => 2,
            (game_id) => 22
        )
    (2) => Array
        (

            (uid) => 1,
            (game_id) => 23
        )
    (3) => Array
        (

            (uid) => 3,
            (game_id) => 24
        )
);

For example User 1 is开发者_StackOverflow in Game 22,23 BUT NOT IN 24 user 3 is in only game 24 I want to find out which user is not participating in other game, Issue is effeciency(speed of execution) and how to represent in array so as i can use it to display.Is it god idea to have it like userid=> notInGame,notInGame (CSV)?


An example of how to do it in PHP:

$array = array(
    array
    (
        'uid' => 1,
        'game_id' => 22
    ),
    array
    (
        'uid' => 2,
        'game_id' => 22
    ),
    array
    (
        'uid' => 1,
        'game_id' => 23
    ),
    array
    (
        'uid' => 3,
        'game_id' => 24
    ),

);

$games = $users = array();

foreach($array as $value)
{
    $games[]                = $value['game_id'];
    $users[$value['uid']][] = $value['game_id'];
}

foreach($users as $uid => $user)
{
    $users[$uid] = array_diff($games, $user);
}

print_r($users);

Result (key is the uid):

Array
(
    [1] => Array
        (
            [3] => 24
        )

    [2] => Array
        (
            [2] => 23
            [3] => 24
        )

    [3] => Array
        (
            [0] => 22
            [1] => 22
            [2] => 23
        )

)


Below is quite simple query if You don't need id of groups. The num field is a number of groups the user is in.

SELECT `uid`, COUNT(*) AS `num`
FROM `a_table`
GROUP BY `uid`;

You will get something like this

$arr2=Array
(
    (0) => Array
        (
            (uid) => 1,
            (num) => 2
        ),

    (1) => Array
        (

            (uid) => 2,
            (num) => 1
        )
    (2) => Array
        (

            (uid) => 3,
            (num) => 1
        )
);
0

精彩评论

暂无评论...
验证码 换一张
取 消