English 中文(简体)
PHP 基于特定数组密钥的 PHP 合并数组
原标题:PHP merging arrays based on specific array key
  • 时间:2012-05-23 02:49:28
  •  标签:
  • php
  • arrays

我有两个基于数组中键值的数组。 在下面的例子中, 我要根据游戏列表中的密钥( id), 将游戏_ 模式放入游戏列表 。

从满桌的游戏中拉动的 数组 1 :

$games_list = array(
  0 => array(
     id  => 23,
     name  =>  Call of Duty: Modern Warfare 3 
    ),
  2 => array(
     id  => 1,
     name  =>  Call of Duty: Black Ops 
    )
  );

从一个充满游戏模式的表格中拉出的数组 2 :

$game_modes = array(
  0 => array(
     id  => 1,
     game_id  => 1,
     description  =>  Capture the Flag 
    ),
  1 => array(
     id  => 2,
     game_id  => 1,
     description =>  Domination 
    ),

  2 => array(
     id  => 3,
     game_id  => 23,
     description  =>  Kill Confirmed 
    )
  );

我希望结果如下:

$games_list = array(
  0 => array(
     id  => 23,
     name  =>  Call of Duty: Modern Warfare 3 
     modes  => array(
        array(
           id  => 3,
           game_id  => 23,
           description  =>  Kill Confirmed 
          )
        )
    ),
  2 => array(
     id  => 1,
     name  =>  Call of Duty: Black Ops 
     modes => array(
      0 => array(
         id  => 1,
         game_id  => 1,
         description  =>  Capture the Flag 
        ),
      1 => array(
         id  => 2,
         game_id  => 1,
         description =>  Domination 
        )
      )
    )
  );

更多信息,我目前正在研究的网站 数据库里有71个游戏 每个游戏都有任意数量的游戏模式

现在,我可以很容易地做一堆循环,并一起回避这个问题。目前,我没有大量游戏模式输入数据库,但我一直在不断添加更多的游戏模式。随着时间推移,不断做更多的循环最终会让页面的负载速度上升。

我花了时间把这些数据放进Memcache 以便让未来的电话更快地避免循环。

我从不擅长阵列图,因为我不太明白它是如何工作的,或者它是否甚至是正确的路线。

最佳回答

Don t you think query level solution would be better? The lengthy way would be:

// array:  $game_modes;
// array:  $game_lists;

foreach ($game_modes as $gm=>$modes){
   if (isset($modes[ game_id ])){
      foreach ($game_lists as $gl=>$lists){
         if ($lists[ id ] == $modes[ game_id ]){
            $game_lists[$gl][ modes ][] = $modes;
            //break;
         }
      }
   }
}

产出类别:汇总

$query =  SELECT 
                g.id, g.name_name,
                group_concat(gm.description) as descriptions
          FROM games as g
          LEFT JOIN games_modes as gm
               ON g.id = gm.game_id
          GROUP BY g.id ;

结果:

  id |  name                     |  descriptions
------------------------------------------------------------
  1  |  Call of Duty: Black Ops  |  Capture the Flag, Domination

产出类别:详细

$query =  SELECT 
                g.id, g.name_name,
                gm.id, gm.description
          FROM games as g
          LEFT JOIN games_modes as gm
               ON g.id = gm.game_id
          ORDER BY g.id ;

结果:

  id |  name                     |  id   |  description
----- --------------------------- ------- ------------------
  1  |  Call of Duty: Black Ops  |   1   |  Capture the Flag
  1  |  Call of Duty: Black Ops  |   2   |  Domination
问题回答

尝试此尝试来减少环绕

$cachearray = array();
foreach ($game_modes as $gm=>$modes){
  if(array_key_exists($modes[ game_id ],$cachearray))
  {
     $cachearray[$modes[ game_id ]][ modes ][] = $modes;
  }
  else         
     foreach ($games_list as $gl=>$lists){
        if ($lists[ id ] == $modes[ game_id ]){
           $games_list[$gl][ modes ][] = $modes;
           $cachearray[$lists[ id ]] = &$games_list[$gl];
           break;
        }
     }
}

print_r($games_list);

如果您有这样的 $games_list 阵列, 将会更容易一些

$games_list = array(
   23 => array(
      id  => 23,
      name  =>  Call of Duty: Modern Warfare 3 
   ),
   1 => array(
      id  => 1,
      name  =>  Call of Duty: Black Ops 
   )
);

使用查询将更强大

如果您想要用户数组映射, 这个代码应该是可能的 :

$ids = array_map(function($game) { return $game[ id ]; }, $games_list);
$id_mapping = array_flip($ids);    

foreach($game_modes as $mode) {
    if (array_key_exists($mode[ game_id ], $id_mapping)) {
        $games_list[$id_mapping[$mode[ game_id ]]][ modes ][] = $mode;
    }
}

但我不知道这是否比循环的速度快。

尝试此选项 :

$mode_map = array();
foreach($game_modes as $mode)
{
    $game_id = $mode[ game_id ];
    if(!isset($mode_map[$game_id]))
    {
        $mode_map[$game_id] = array();
    }

    $mode_map[$game_id][] = $mode;
}

foreach($games_list as &$game)
{
    $game_id = $game[ id ];
    if(isset($mode_map[$game_id]))
    {
        $game[ modes ] = $mode_map[$game_id];
    }
}

print_r($games_list);

结果:

Array
(
    [0] => Array
        (
            [id] => 23
            [name] => Call of Duty: Modern Warfare 3
            [modes] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [game_id] => 23
                            [description] => Kill Confirmed
                        )

                )

        )

    [2] => Array
        (
            [id] => 1
            [name] => Call of Duty: Black Ops
            [modes] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [game_id] => 1
                            [description] => Capture the Flag
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [game_id] => 1
                            [description] => Domination
                        )

                )

        )

)




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签