|
Posted by Chung Leong on 11/04/05 02:30
Ah, you got confused by JDS's cryptic message. To return an array, you
just return it. A call to array() would create a new array with
whatever passed as its elements. For example, the following would give
you an array with 2 elements, "Hello" and "World".
$array = array("Hello", "World");
The following is what you need to create a array of arrays:
function test()
{
$array[0][0] = "Hello";
$array[0][1] = "World";
$array[1][0] = "How Are";
$array[1][1] = "You?";
return $array;
}
I said "array of arrays" instead of "2-D array" because that's what
they are. Strictly speaking, the function doesn't create one 2-D array;
it creates three arrays--two inside the third. We could've created the
same structure with the following:
function test()
{
$array = array(
array("Hello", "World"),
array("How are", "You?")
);
return $array;
}
or
function test()
{
$array = array();
$array[] = array("Hello", "World");
$array[] = array("How are", "You?");
return $array;
}
Personally I prefer the last syntax, as it's more obvious what's
happening: (1) an empty array is created (2) a new array with two
strings is added (3) another array with two strings is added.
Now going back to your code, you could have coded the while loop like
this
while($arr=mysql_fetch_array($qry))
{
$cat[] = array($arr['cat_id'], $arr['name']);
}
Navigation:
[Reply to this message]
|