title: Accessing multi-dimensional, unordered, associative arrays in an ordered fashion using an incremental loop
body: <p>This is primarily a PHP answer, but the methodology may in fact be language agnostic.</p>
  
  <p>After running a CSV file through a simple parser, I was given a multidimensional array that resembled something akin to this:</p>
  
  <pre><code>array( 'estimated' =&gt;
    array( 
      array( "TITLE" =&gt; 'MAIN', "CURR_PERF" =&gt; 100, "POT_PERF" =&gt; 75 ),
      array( "TITLE" =&gt; 'HEAT', "CURR_PERF" =&gt; 90, "POT_PERF" =&gt; 60 ),
      array( "TITLE" =&gt; 'CO2', "CURR_PERF" =&gt; 56, "POT_PERF" =&gt; 40 ),
    ),
  
   'actual' =&gt; 
     array(
      array( "TITLE" =&gt; 'MAIN', "CURR_PERF" =&gt; 100, "POT_PERF" =&gt; 75 ),
      array( "TITLE" =&gt; 'HEAT', "CURR_PERF" =&gt; 89 , "POT_PERF" =&gt; 75),
      array( "TITLE" =&gt; 'CO2', "CURR_PERF" =&gt; 40, "POT_PERF" =&gt; 20 ),
     );
  );
  </code></pre>
  
  <p>Now, horrific data structure to one side, without refactoring of the underlying parser - how would be the best way to ensure that you can access these in a specific order? <strong>Without necessarily touching the underlying parser?</strong></p>
  
  <p>If you loop through using a <code>for()</code>/<code>foreach()</code> loop you're only going to be able to read them in a linear order - increasing or decreasing down the elements. You're not necessarily going to be able to drill down and get the specific value required.</p>
  
  <p>For instance, the CSV file could express the values for <code>estimated</code> in a different order to the values for <code>actual</code>; and it may be required that they are output in yet another order.</p>
  
  <p>For example, here are three different orders off the top of my head:</p>
  
  <pre><code>-&gt; MAIN HEAT CO2
  -&gt; HEAT MAIN CO2
  -&gt; CO2  HEAT MAIN
  </code></pre>
  
  <p>Furthermore, as is quite usual, the label names in the CSV file are not exactly user-friendly - so they need to be '<em>translated</em>' (if you like) in to something more human-friendly. Naturally, without the use of lots of <code>if()</code> statements if preferable!</p>
  
  <p>Given it's a very specific use case, but it's something I've seen before with regards to arrays being serialised - and often finding out that they are actually nested.</p>
  
  <p>I've posted one possible solution, but would be happy to see others. (In the past when I've done similar I've never accepted my own answer ;)) I'm sure there must be a more elegant way than the one I've devised..!</p>