Merging Two Arrays of Different Size (PHP)

This isn’t pretty, but I needed to write code that would merge two arrays of differing sizes. One contained injury information for 1400 players with an overlapping field of elias_id with an array of 900 players of PITCHf/x data. Simply put, I needed to insert two values from the injury array to matching players in the PITCHf/x array.

Here’s how I did it with array_search() and preg_replace() – the arrays were in the format of $pitcher[‘elias_idxxx’] where xxx was the numeric point at which the value was in (so elias_id0 through elias_id899 for the PITCHf/x array and elias_id0 through elias_id1399 for the injury array).

Whether or not the arrays are properly formatted and constructed is not the point of this blog post. (Though it is likely that it is better done through a second recursive array, we’re not selling code here. We’re selling functionality.)

[php]
$x = 0;
$y = 0;
$pattern = ‘/[^0-9]/’;

if (!@$pitcher){
// do nothing
}
else // parse the array
{
foreach($pitcher as $blank)
{
$key = array_search($pitcher[‘elias_id’ . $x], $injuries);
if ($key)
{
$y = preg_replace($pattern, ”, $key);
$pitcher[‘timesinjured’ . $x] = $injuries[‘timesinjured’ . $y];
$pitcher[‘daysmissed’ . $x] = $injuries[‘daysmissed’ . $y];
}
$x++;
if (!@$pitcher[‘elias_id’ . $x])
break;
}
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *