我有两个数组,第一个数组:
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'
两个数组都比上面的要长得多。现在,我想运行第二个数组并在其中创建NEW属性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。
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);
假设第一个数组是$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演示
首先,我们迭代children数组,创建一个键为[HouseFk][ConstructionTypeFk]
的新数组($discounts
),然后很容易迭代主数组,添加适当的->discounts
属性:如果在$discounts
数组中有一个元素具有[PkID][ConstructionTypeFk]
键,我们可以添加它。