Hi monks! I have two arrays of hash references, I've put a single element of each of them below. In both arrays each hash contains a 'year', 'month', 'day', 'hhmm' key and value. I then have different keys and values in each array (data1 in array1 and data2 in array2).
$array1[0] = { 'day' => '02', 'year' => '2003', 'month' => '06', 'hhmm' => '0900', 'data1' => '5' }; $array2[0] = { 'day' => '02', 'year' => '2003', 'month' => '06', 'hhmm' => '0900', 'data2' => '6' };
What I'm trying to do is to merge the two arrays into one, so that if 'year', 'month', 'day', 'hhmm' all match then both 'data1' and 'data2' keys and values appear in the new array. The arrays are not the same size, as one contains data for every 30 minute, the other for every 5 minues. If there is no match between the two arrays I still want to keep the data in the new array.
$array3[0] = { 'day' => '02', 'year' => '2003', 'month' => '06', 'hhmm' => '0900', 'data2' => '6', 'data1' => '5' };
I first tried using a pair of nested loops, but unsuprisingly this was very slow! I'm now thinking of a more efficient way of doing this. The arrays are sorted. My current plan was to loop through the larger of the two arrays and create an index of the position of the first hour of each day. Then while looping through the smaller array lookup in this index to find a place to start looking in the larger array. However as I'm sure there are thousands of different ways to do this, I though I'd ask for some wisdom! So is there a better, simpler, quicker, prettier, or other way to do this? Thanks very much

In reply to Combining arrays of hashes by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.