如何在PHP中将数组的结果分为两类?

时间:2012-08-11 15:27:35

标签: php arrays multidimensional-array grouping

我这里有数据:

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]))

2 个答案:

答案 0 :(得分:1)

你应该选择的是数组:

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

以后使用数组$ owner,如:

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;    
}

答案 1 :(得分:0)

您需要做的就是遍历初始数组,将每个OwnerAID附加到SiteID确定的相关输出子数组中:

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

我在这里使用以下功能: