如何以多维方式创建新键并存储数组值PHP

时间:2012-08-17 07:55:39

标签: php arrays multidimensional-array merge

我这里有数据:首先,我的第一个函数名为getsiteaccounts()

Array
(
[0] => Array
    (
        [SiteID] => 2
        [AID] => 5
    )

[1] => Array
    (
        [SiteID] => 2
        [AID] => 3
    )
[2] => Array
    (
        [SiteID] => 6
        [AID] => 4
    )

我的第二个函数的结果名为bindGHComponentsToSites()

   Array
  ( 
  [2] => Array
    (
        [SiteID] => 2
        [Balance] => 19000.00
        [MinBalance] => 100000.00
        [MaxBalance] => 1000000.00
        [OwnerAID] => 5
        [GroupID] => 1
        [Deposit] => 1500
        [Reload] => 1000
        [Redemption] => 1000
    )

)

然后,添加指向OwnerAID列表的[CorpAID]键。顺便说一下,OwnerAID和AID是一样的。正如您所见,SiteID => 2由两个OwnerAID拥有=> 5和3.这应该是结果:

   Array([0])=> Array (
        [SiteID] => 2
        [Balance] => 19000.00
        [MinBalance] => 100000.00
        [MaxBalance] => 1000000.00
        [OwnerAID] => 5
        [GroupID] => 1
        [Deposit] => 1500
        [Reload] => 1000
        [Redemption] => 1000
        [CorpAID] => Array(
                   [0] => 5
                   [1] => 3
        )
      )
  )

SiteID => 6不应该打印,因为它只拥有一个AID。有可能成功吗?请以正确的方式指导我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用几个foreach循环来执行您需要的操作:

<?php

$siteAccounts = array(
  array('SiteID'=>2, 'AID'=>5),
  array('SiteID' => 2, 'AID' => 3),
  array('SiteID' => 6, 'AID' => 4)
);

$componentsToSites = array(array(
  'SiteID' => 2,
  'Balance' => 19000.00,
  'MinBalance' => 100000.00,
  'MaxBalance' => 1000000.00,
  'OwnerAID' => 5,
  'GroupID' => 1,
  'Deposit' => 1500,
  'Reload' => 1000,
  'Redemption' => 1000
));

foreach ($componentsToSites as &$site) {
  $aids = array();
  foreach ($siteAccounts as $acct) {
      if ($acct['SiteID'] === $site['SiteID'])
        $aids[] = $acct['AID'];
  }
  $site['CorpAID'] = $aids;
}

print_r($componentsToSites);

修改

我的原始答案使用array_walk而非foreach,但由于兼容性问题,我将其切换。以下是使用array_walk的原始代码段:

array_walk($componentsToSites, function (&$site) use ($siteAccounts) {
  $aids = array();
  array_walk($siteAccounts, function ($acct) use ($site, &$aids) {
      if ($acct['SiteID'] === $site['SiteID'])
        $aids[] = $acct['AID'];
  });
  $site['CorpAID'] = $aids;
});