Avatar of KOvitt
Flag for United States of America asked on

Loop through multi dimensional array

I have a multi dimensional array in PHP that includes

Array([0] => Array ( [0] => Week 10 - 2011 [1] => 384266.0 [2] => APPL))
Array([1] => Array ( [0] => Week 10 - 2011 [1] => 364266.0 [2] => BLK))

A Date in the first element on the imbedded array, volume in the second and a ticker in the third.

My array can be up to 6000ish long. And Dates repeat for different tickers, and tickers repeat for different dates.

The dates can be either days, weeks, months, Quarters or years

I want to loop through the array and display it in an html table with the following format

                Date1    Date2    Date3    Date4  ....
Ticker1   Volume  Volume  Volume  Volume
Ticker2   Volume  Volume  Volume  Volume
Ticker3   Volume  Volume  Volume  Volume
Ticker4   Volume  Volume  Volume  Volume
...           ...           ....          ....          ....

It displays the ticker on the y axis and the date on the x. Then displays the volume for the corresponding ticker on that date.

How would I loop through the array to do this?



Avatar of undefined
Last Comment

8/22/2022 - Mon

foreach($arr as $key => $array2) {
   foreach($array2 as $key2 => $val) {
     //echo "";

your multi-dimensional "starting array" is not in an ideal format for doing this. How is it created? Is there an opportunity to change its creation as well, or would you like this solution to based solely on what you have there?

I have a SQL query that I loop through with mysql_fetch_array and then dump it into a new array
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck

Also, each ticker and date can only be on their corresponding axis once
Beverley Portlock

Note that using foreach will result in all the data being replicated as foreach works on a COPY of the data. To avoid this you need to work either with for loops or modify the foreach to use references.

The danger is that if you have a lot of data stored in memory then you will soon use up all the spare memory. Also the duplication can lead to unexpected results. For instance this code

$arr = array( 1, 2, 3, 4 );

foreach( $arr as $aValue )
    $aValue = '99';

print_r( $arr );

Open in new window

will have no effect on the original array values at all

Kovitt, I understand exactly what you want. Without a larger sample of data, it's hard to test perfectly, but here we are. I think this could be made much more efficient by changing the way the SQL query is dumped into the starting array though.

Give this a shot. The only challenge I know of is that it will not sort the dates:

    $data = Array(Array('Week 10 - 2011', 384266.0, 'APPL'),
                  Array('Week 10 - 2011', 364266.0, 'BLK'));

    // First, get a list of all the possible dates.
    // This allows us to create a list of "column ids" for the resulting table
    $dCnt = 0;
    foreach ($data AS $inlineArr) {
        if (!isset($dates[$inlineArr[0]])) {
            $dates[$inlineArr[0]] = $dCnt;

    // Now, create a new data structure by ticker ID, separating each volume into the correct column ID
    foreach ($data AS $inlineArr) {
        $newData[$inlineArr[2]][$dates[$inlineArr[0]]] = $inlineArr[1];

    // Finally, create the table:
    echo "<table>\n";

    // Column Headers:
    echo "<tr><th>Ticker</th><th>".implode("</th><th>",array_keys($dates))."</th></tr>\n";

    // Data:
    foreach ($newData as $ticker => $volumes) {
        echo "<tr><td>$ticker</td>";
        for ($i=0;$i<count($dates);$i++) {
            if (isset($volumes[$i])) {
                echo "<td>{$volumes[$i]}</td>";
            } else {
                echo "<td>&nbsp;</td>";
        echo "</tr>\n";
    echo "</table>\n";

Open in new window

Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.

Kovitt, if you post the SQL query code and creation of that datastructure, we may be able to clean this up. The solution I posted above has some overhead because it has to loop through the entire array a few times while creating a new one.

m4trix, you are awesome!!!! Thank you soo much, it worked perfectly! Any thoughts as to how we can get the dates in order? Sort the Array before maybe?

Kovitt, yes, exactly, but it may not sort properly because right now your dates are formatted like "week 10 - 2011" - which is not an easy sort to do without converting to a number. sorted by string you would end up with "week 9 - 2011" coming after "week 10 - 2011"

Would you be able to changet the format of the dates going into the initial array?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy

absolutely, I can change it to anything. any suggestions as to what to display that is sortable for both weeks and quarters? The rest should be fine as year is simply (ex: 2009) and Day is (ex: 2009-04-30) ect

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.

Thank you SOOOOOOOOO much!!!!! :D

You Rock!