duanchen1937 2016-04-05 14:42 采纳率: 0%
浏览 19
已采纳

添加元素对象属性匹配的数组元素

I have two arrays, First array:

array (size=3)
  0 => 
    object(stdClass)[31]
      public 'PkID' => string '489' (length=3)
      public 'HouseFk' => string '22' (length=2)
      public 'ConstructionTypeFk' => string '1' (length=1)
      public 'Price' => string '666' (length=3)
      public 'discount_id' => string '1' (length=1)

Second array:

array (size=2)
  0 => 
    object(stdClass)[28]
      public 'PkID' => string '22' (length=2)
      public 'ArchitectFk' => string '13' (length=2)
      public 'ShortVersion' => string '169' (length=3)
      public 'Subtitle' => string '' (length=0)
      public 'Size' => string '170.29' (length=6)
      public 'ConstructionTypeFk' => string '1'

Both arrays are much longer than above. Now I want to run through the Second array and create NEW property public 'discounts' inside this property will be the array with all the first array elements that match.

In another words for every element of the second array I want to check where the HouseFk in first array is the same as the PkID of the current element and where the ConstructionTypeFk is the same as the current element and add those matches inside current element.

Something in the lines of:

foreach ($second_array as $value)
{
    $value->discounts[] = first array element where HouseFk is equal to $value->PkID and ConstructionTypeFk is equal to $value->ConstructionTypeFk;
}

I can build pseudo code and know what to do, I just don't know what to use. I tried reading about array_filter but I don't think I can use it to search for two object properties....

  • 写回答

2条回答 默认 最新

  • douyuan4357 2016-04-05 16:12
    关注

    Assuming your first array is $array1 and your second array is $array2:

    $discounts = array();
    foreach( $array1 as $row )
    {
        $discounts[$row->HouseFk][$row->ConstructionTypeFk][] = $row;
    }
    
    foreach( $array2 as $row )
    {
        if( isset($discounts[$row->PkID][$row->ConstructionTypeFk]) )
        {
            $row->discounts = $discounts[$row->PkID][$row->ConstructionTypeFk];
        }
    }
    

    <kbd>eval.in demo</kbd>

    First we iterate children array, creating a new array ($discounts) with keys as [HouseFk][ConstructionTypeFk], then it's easy, iterating main array, to add the appropriate ->discounts property: if in $discounts array there is an element with [PkID][ConstructionTypeFk] key, we can add it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?