【问题标题】:Add array element where elements object property matches添加元素对象属性匹配的数组元素
【发布时间】:2016-07-25 14:03:08
【问题描述】:

我有两个数组,第一个数组:

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)

第二个数组:

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'

两个数组都比上面的长得多。 现在我想遍历第二个数组并在该属性内创建新属性public 'discounts' 将是所有第一个数组元素匹配的数组。

换句话说,对于第二个数组的每个元素,我想检查第一个数组中的HouseFk 与当前元素的PkID 相同,以及ConstructionTypeFk 与当前元素相同的位置并在当前元素中添加这些匹配项。

以下内容:

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

我可以构建伪代码并且知道该做什么,但我不知道该使用什么。我尝试阅读有关 array_filter 的信息,但我认为我不能使用它来搜索两个对象属性....

【问题讨论】:

  • 为什么不呢?使用 array_filter 您可以定义一个回调,您可以在其中定义何时返回 true 或 false。
  • @slax0r 因为我需要找到二级维度数组的两个属性相同的位置并返回其键

标签: php arrays


【解决方案1】:

就像上面评论中已经说过的那样,您可以按照您的意图安全地使用 array_filter 来实现此目的,因为在其中,您定义了一个回调,它可以根据需要处理条件,并且没有无论数组值有多深或您希望检查多少个值,您所需要做的就是在最后为您要保留的元素返回 true。

foreach ($second_array as &$secondValue) {
    $secondValue->discounts[] = array_filter(
        $first_array,
        function ($firstValue) use ($secondValue) {
            return $firstValue->HouseFk === $secondValue->PkID
                && $firstValue->ConstructionTypeFk === $secondValue->ConstructionTypeFk;
        }
    );
}
// now just unset the reference to $secondValue
unset($secondValue);

【讨论】:

    【解决方案2】:

    假设您的第一个数组是$array1,而您的第二个数组是$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];
        }
    }
    

    eval.in demo

    首先我们迭代 children 数组,创建一个新数组 ($discounts),键为 [HouseFk][ConstructionTypeFk],然后很容易,迭代主数组,添加适当的 ->discounts 属性: if在$discounts数组中有一个带有[PkID][ConstructionTypeFk]键的元素,我们可以添加它。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 2013-02-19
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多