0

I count the amount of columns (fields) in a DB, now I want to create an array for each column. Is this somehow possible? For example:

$num = mysql_num_fields($query);
for($i=0; $i<$num; $i++){     // loop 1
    $field_names[] = mysql_field_name($query,$i);
}
for($i=0; $i<$num; $i++){    // loop 2
    while($row = mysql_fetch_array($query)){  // loop 3
        $array[] = $row[$field_names[$i]]
    }
}

Now I basically want the $array[] variable to change every time loop 2 ends so that at the end of say 3 loops I'd have 3 different arrays. Is that possible? If so can someone please explain?

Stuyvenstein
  • 2,340
  • 1
  • 27
  • 33
  • Could you give an example with the expected result? – Julien Bourdon Jul 21 '12 at 05:18
  • instead of doing mysql_fetch_array, look into mysql_fetch_assoc. Might help you out more – Kris Jul 21 '12 at 05:21
  • And try to use mysqli, if it's new code since it works better. http://stackoverflow.com/questions/171400/which-is-fastest-in-php-mysql-or-mysqli – Julien Bourdon Jul 21 '12 at 05:21
  • Say for example the db table has x amount of fields, I want to run that same x amount of loops and in each loop I want to create a new array. Say x = 3 then I want to end up with array1[], array2[] and array3[] – Stuyvenstein Jul 21 '12 at 05:22
  • Creating arrays is easy. `for ($i = 0, $l = 3; $i < $l; $i += 1) { $array = array(); $array[] = X; }`. Why do you want that? What do you want to do with them, before they disappear, or you can't access them, because you don't know what they're called? What do you actually want to put in the arrays or do with them? If you're trying to create a 2D matrix, you'd probably be better off making that, first. – Norguard Jul 21 '12 at 05:28

2 Answers2

1

Instead of an array for each column you can create a array with field name as a key.

$num = mysql_num_fields($query);
for($i=0; $i<$num; $i++){     // loop 1

    $field_names = mysql_field_name($query,$i);
    $field_array[$field_names] = array();
}

after this you will get the following array

print_r($field_array);

//out put

Array(
[fieldname1] => Array() 
[fieldname2] => Array() 
[fieldname3] => Array() 
[fieldname4] => Array() 
)
Shahid Ahmed
  • 494
  • 2
  • 4
  • 10
0

Im not sure why you would want to do that.. but it is possible..

for($i=0; $i<$num; $i++){    // loop 2
    while($row = mysql_fetch_array($query)){  // loop 3
        $arrayName = "array$i";
         ${$arrayName}[] = $row[$field_names[$i]]
    }
}

So if you had 3 loops you will have $array1, $array2, $array3 variables

But again, I would really advise against this and rethink your design, there must be a much better way to do it.

Kris
  • 6,094
  • 2
  • 31
  • 46