0

我这里有数据:

Array
(
[1] => Array
    (
        [SiteID] => 1
        [OwnerAID] => 1

    )

[3] => Array
    (
        [SiteID] => 3
        [OwnerAID] => 1

    )

[6] => Array
     (
        [SiteID] => 6
        [OwnerAID] => 2

     )
    )

现在,我需要将它们OwnerAID分为两类:第一个是OwnerAID只拥有一个SiteID,第二个是OwnerAID拥有多个 1 SiteID

我试图制作一个程序并进行一些研究,但我的代码输出是错误的。

请看我的代码:

       public function groupIndividualAndAggregateSites()
    {

    $arrays = array();
        foreach($this->combined as $key => $key_value)
        {
            $SiteID = "";

        if ($SiteID == "") {

            $SiteID=array($key_value['SiteID']); }

           else {
                   $SiteID = array_merge((array)$SiteID, (array)$key_value['SiteID']);

                   $SiteID = array_unique($SiteID);

                }

       } if ($SiteID != "") {

       $arrays = array('AID'=>$key_value['AID'], 'Sites' => $SiteID);
     }
        print_r($arrays);

    }

结果应如下所示:

 Array( 
        [1] => Array

      ( [Sites] => Array ([0] => 1, [1] => 3)))

 Array( 
        [2] => Array

      ( [Sites] => Array ([0] => [6]))
4

2 回答 2

1

你应该去的是数组:

$owners = array(
owner_1 => SiteID1, // int Only one site
owner_2 => array (SiteID2,SiteID3), // array Multiple sites
);

然后使用数组 $owners 像:

echo (is_array($owners[$owner_1]) ? 'Has multiple sites' : 'has one site';

这就是小内存占用的基本思想。

示例,未经测试。

public function groupIndividualAndAggregateSites() {
  $owners = array();
  foreach($this->combined as $key => $value) {
    $owner_id = $value['OwnerAID'];
    $site_id = $value['SiteID'];

    if(array_key_exists($owner_id,$owners)) {
      // He has one or more sites already?
      if(is_array($owners[$owner_id]){
        array_push($owners[$owner_id],$site_id);
      } else {
      // User already has one site. Lets make an array instead and add old and new siteID
        $old_site_id = $owners[$owner_id];
        $owners[$owner_id] = array($old_site_id,$owner_id);
      }
    } else {
      $owners[$owner_id] = $site_id;
    }
return $owners;    
}
于 2012-08-11T15:45:01.573 回答
0

您需要做的就是遍历您的初始数组,将每个数组附加OwnerAID到相关的输出子数组,具体取决于SiteID

$output = array(1=>array(), 2=>array());
foreach ($original as $v) $output[$v['SiteID'] == 1 ? 1 : 2][] = $v['OwnerAID'];

在这里,我使用以下功能:

于 2012-08-11T15:41:11.843 回答