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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路