0

我这里有数据:首先,我的第一个函数名为 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 拥有。有可能做到吗?请以正确的方式指导我。先感谢您。

4

1 回答 1

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;
});
于 2012-08-17T08:19:52.930 回答