how to create a multidimensional array PHP

10,717

Solution 1

You have to put the date as the array key, like so:

$my_multi_array[$date]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));

Notice the $my_multi_array[$date].

By doing $my_multi_array[] = ... you are just creating a new numerical index on the array with the content on the right side. That's why when you access the array with the numerical index, like $my_multi_array[2], it works.

On the other hand, by doing $my_multi_array[$date]you are treating the array like an hash table, where you associate a key (in this case a string containing a date) with a value.

Solution 2

Everything is correct, because you don't have array('key' => 'value') style array, instead of that you've got array( [0] => array( 'key' => 'value' ) ) that's why you're getting correct result on accessing numeric key of the array.

Share:
10,717
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have some data for my sites statistics in a SQL DB:

    date:          visits:        pageviews:
    12-12-12       34             21
    12-12-13       31             22
    12-12-14       33             2445
    12-12-15       35             2422
    12-12-16       36             232
    
    //ect ect
    

    I'm trying to create a Multidimensional array that contains all the dates info from the DB and where the date will be the key (selector,name of the array inside the multi array), so as the end result, I should be able to just do this:

    print_r $my_multi_array[12-05-12];
    

    And I should see the statistics for that date on the screen.

    Now I know how to do all the loops and stuff, and I even have a good idea about how to do multidimensional arrays, it's just that I think I'm doing something wrong:

    //first things first, define the array:
    $my_multi_array=array();
    
    //then, in a loop, append to the array:
    $my_multi_array[]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));
    

    Now when I print_r that array, everything looks good:

    Array ( [0] => Array ( [11-12-24] => Array ( [visits] => 1 [pageviews] => 0) ) [1] => Array ( [11-12-25] => Array ( [visits] => 1 [pageviews] => 0) ) [2] => Array ( [11-12-26] => Array ( [visits] => 1 [pageviews] => 0)))1
    

    Notice the 1 at the end ^^. That seemed to be in the result (not a typo).

    Now when I try printing a certain array out (using the date as the key):

    print_r $my_multi_array['11-12-24'];
    

    I get:

    1
    

    So then i try:

    print_r $my_multi_array[2];
    

    and that works fine.

    For some reason, it wont let me select an array from $my_multi_array using the date as the key.

    Any ideas on how to fix this?

    thanks