Welcome to WebmasterWorld Guest from 54.211.136.250

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Function to separate array created by mysql fetch array

   
3:52 pm on Dec 12, 2011 (gmt 0)

5+ Year Member



Hi all,

I create an array using the $row = mysql_fetch_array($result,MYSQL_BOTH)function.

It's great because i can reference an element value using either the numeric or associative key. However, I need to pass only the numeric keyed portion of the array as a json string back to the client side.

Is there a PHP function that will separate numeric array from the associative array?

I checked the php site but could not find any so i thought i'd check with you all.

thanks.
4:25 pm on Dec 12, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



MYSQL_BOTH is actually the default, as if no 2nd argument is passed. Can you not simply pass MYSQL_NUM in order to return an array with only numeric indices, or do you need the column names elsewhere in your script?
1:20 am on Dec 13, 2011 (gmt 0)

5+ Year Member



I use the associative indices to easily assign values to the elements without having to count or remember which numeric index it is. However, when i construct the json object before encoding it and sending it to the client side, i want to use the numeric key array.
7:44 am on Dec 13, 2011 (gmt 0)

5+ Year Member



This will do what you want:

while ($row = mysql_fetch_array($result)) {
ksort($row, SORT_STRING); //will order $row so all numeric indices are first
$tmp = array_slice($row, 0, count($row) / 2); //all the numeric indices from $row
//do something with $tmp
}
4:38 pm on Dec 13, 2011 (gmt 0)

5+ Year Member



great, thanks. I'll look at the solution asap.

Happy Holidays!