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....
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];
}
}
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.
Like already said in comment above, you can safely use array_filter for this purpose as you already intended, because in it, you define a callback, which handles conditions just as you want them, and no matter how deep into array values or how many values you wish to check, all you need to do is return true at the end, for the element that you want to keep.
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);