Log in

View Full Version : Resolved get the index from mysql_fetch_array



ggalan
05-14-2012, 12:41 AM
if i have a query that outputs with order

$query0 = mysql_query("SELECT name FROM mytable ORDER BY numVar");
$result0 = mysql_query($query0);

while ($row0 = mysql_fetch_array($result0)){
$name = $row0['name'];
}

if the result = g, b, r, c
how can i find the index number of say 'r' ?
is there a way of doing something like

foreach ($sub as $key => $value) {
}

ApacheTech
05-14-2012, 01:22 AM
By "index", do you mean the index within the generated array, or the index of where it was originally positioned in the db (it's id)?

ApacheTech
05-14-2012, 01:30 AM
For the former, try using array_search (http://php.net/array_search)



<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>


For the latter, you'll need to add the mytable_ID field to the SELECT statement, if you have one. If you don't have one then you'll have to create an AutoNumber field in the table. (For this, it's best to build a new table from scratch and repopulate it)



<?php
$query1 = mysql_query("SELECT id, name FROM mytable ORDER BY name");
?>

ggalan
05-14-2012, 02:05 AM
i need to make a sql query within a query to look for a rows index within a subset
i think pushing items into an array then use 'array_search' should do it
thanks

ApacheTech
05-14-2012, 02:22 AM
i need to make a sql query within a query to look for a rows index within a subset

That hurt my head just reading it! :confused:




// mytable record field "names: ['d', 'b', 'a', c']"

$sql = "SELECT name FROM mytable ORDER BY name";
$result = mysql_query($sql); // ['a', 'b', 'c', d']

$key = array_search('a', mysql_fetch_array($result)); // $key = 2;


Maybe?