Search code examples
phpmultidimensional-arrayparent-childlevels

How to break down a php array with levels?


I have a MySQL table with stock information including what main industry sector and sub sector a stock belongs to (for example the Coca-Cola stock belongs to the industry sector "Consumer Goods" and to the sub sector "Beverages - Soft Drinks".

$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());

while ($row = mysql_fetch_row($result)) {

 $stocks[$i]['name'] = $row[0];
 $stocks[$i]['industrysector'] = $row[1];  
 $stocks[$i]['subsector'] = $row[2]; 

 $i++;
}

$stocksTotals = array();

foreach($stocks as $amount) { 
    $stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name']; 
}

foreach($stocksTotals as $name => $amount) {    echo $name.": ".substr($amount,1)."<br>"; }  

My problem is that I don't get the code to handle the third level. I want to first output all of the industry sectors (Basic material for example), then all subsectors (Basic Resources for example) for each industry sector, then all names of the stocks corresponding to each subsector.

Currently I only get industry sector and then the stock name, because I fail to understand how to handle this in the array handling code.

Any advise would be highly appreciated! I have put a image here (http://imageshack.us/photo/my-images/853/mysqltophp.gif/) for better reference.

Thanks!


Solution

  • the foreach loop needs to be like this:

     //considering you want the value as "$amount['industrysector'], $amount['name']" 
    foreach($stocks as $amount) { 
    // $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name']; 
      echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
     }
    

    you dont need another foreach loop.

    Edit: you would need to change the way you fetch your rows too,

    while ($row = mysql_fetch_assoc($result)) {
      $stocks[$i]['name'] = $row['name'];
      $stocks[$i]['industrysector'] = $row['industrysector'];  
      $stocks[$i]['subsector'] = $row['industrysector']; 
      $i++;
     }
    
    
    
    foreach($stocks as $amount) { 
     $output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
     if( $amount['name'] !== '' )
       $output .= "<br>" . $amount['name'];
     ";
    }