Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This was the quickest (and neatest) solution I could come up with on the spot at the time, but it's not one that I take very much pride in..! It involves multiple loops, the use of several arrays and seems to be an over-engineered mechanism for doing something which should surely be pretty simplistic?</p> <p>First of all I've created an associative array to use as a dictionary to look up translations for text strings found in the CSV file:</p> <pre><code>$tbl = array( "MAIN"=&gt;"Main Costs", "TOTAL"=&gt;"Total Costs", "CO2"=&gt;"Gas expended" ); </code></pre> <p>Next up, I created an array to use as an 'index' - I entered the <code>key</code> values here in the order I would like them to be accessed in the application:</p> <pre><code>$index = array( "MAIN", "TOTAL", "CO2" ); </code></pre> <p>I then created two blank arrays and populated them with the data from the child arrays, by using a loop I was able to make them associative - allowing me to specify use the <code>TITLE</code> fields as keys:</p> <pre><code>$estimated = array(); $actual = array(); foreach( $bills['estimated'] as $bill ){ $estimated[ $bill['title'] ] = $bill; } foreach( $bills['actual'] as $bill ){ $actual[ $bill['title'] ] = $bill; } </code></pre> <p>By doing this I could loop through them in a specific order, regardless of the order they were parsed in, like so:</p> <pre><code> for($i=0; $i&lt;3; $i++){ $bill = $estimated[ $index[ $i ] ]; printf(" %s: %d ", $tbl[ $index[ $i ] ], $bill['CURR_PERF'] ); } </code></pre> <p>Which would output the following, in the order I specified:</p> <pre><code>// 1. Main Costs: 100 // 2. Total Costs: 90 // 3. Gas Expended: 56 </code></pre> <p>Naturally, this order could easily be changed if required. It does however:</p> <ul> <li>require using an array specifically to act as an index</li> <li>require using two loops simply to initialise</li> <li>uses a total of four extra arrays</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload