Jump to content

Compare And Merge Multidimensional Array Values


matthewtbaker

Recommended Posts

Hi phpfreak-ers,

 

$BigArray[] = array('url' => 'www.example.com', 'referer' => 'refer1');

$BigArray[] = array('url' => 'www.demo.com', 'referer' => 'refer1');

$SmallArray[] = array('url' => 'www.example.com', 'referer' => 'refer2');

 

Basically I want to compare the two example arrays (above) and if a duplicate 'url' is found then I'd like to merge the 'referer' values in $BigArray otherwise add as an additional record.

 

So I should be left with:

 

Not syntax just used to explain my objective

$BigArray url='www.example.com', 'referer' = 'refer1refer2'.
$BigArray url='www.demo.com', 'referer' = 'refer1'.

 

I've tried a day and a half worth of approaches and can't get it working.

Thanks for your help in advance!

 

Matt

  On 10/26/2012 at 10:31 AM, pbs said:

Try using PHP "array_intersect()" function.

 

Hi pbs,

 

From what I can work out the array_intersect() function does not seem to support multidimensional arrays. It also does not merge values depending on whether a specified key matches or not.

Off the top of my head something like this should be close:

for($i=0;$i<=count($smallArray)-1;$i++){
 foreach($bigArray as $sdArray){
   if($smallArray[$i]['url'] == $sdArray['url']){
  $sdArray['refferer'] = $sdArray['refferer'].$smallArray[$i]['refferer'];
   }
 }
}

  On 10/26/2012 at 12:35 PM, Muddy_Funster said:

Off the top of my head something like this should be close:

for($i=0;$i<=count($smallArray)-1;$i++){
foreach($bigArray as $sdArray){
if($smallArray[$i]['url'] == $sdArray['url']){
 $sdArray['refferer'] = $sdArray['refferer'].$smallArray[$i]['refferer'];
}
}
}

 

Thanks Muddy_Funster but unfortunately this does not work.

Basing my approach on Muddy_Funster I came up with the below which successfully resolves the original question. I thought I would share it in case anyone comes across this post in the future.

 

for ($iBigArrayIndex = 0; $iBigArrayIndex < sizeof($iBigArrayIndex); $iBigArrayIndex++) {
for ($iSmallArrayIndex = 0; $iSmallArrayIndex < sizeof($SmallArray); $iSmallArrayIndex++) {
 if ($SmallArray[$iSmallArrayIndex]['url'] == $BigArray[$iBigArrayIndex]['url']) {
	 $BigArray[$iBigArrayIndex]['referrer'] = $BigArray[$iBigArrayIndex]['referrer'] . ',' . $SmallArray[$iSmallArrayIndex]['referrer'];
 } else {
	 $BigArray[] = array('url' => $SmallArray[$iSmallArrayIndex]['url'], 'referrer' => $SmallArray[$iSmallArrayIndex]['referrer']);
 }
}
}

 

I was surprised that there was not a standard PHP function that does this.

 

Does anyone have a neater/cleaner way of doing this?

 

Matt

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.