How to get the row index?

I have a database table:

ID name 15 name1 27 name2 39 name3 

I need to assign the indices of these strings, for example: name1 should have index 0, name2 - index 1, name3 - index 2:

 ID name index 15 name1 0 27 name2 1 39 name3 2 

I am trying to do this with a loop:

 $sub = $wpdb->get_results("SELECT t.* FROM $wpdb->terms AS t, $wpdb->term_taxonomy AS tt WHERE tt.parent = $termID AND tt.term_id = t.term_id "); $i=-1; foreach ($sub as $key) { $i++; $number[$i]=$i; } 

The result of this loop:

 $number[0]=0; $number[1]=1; $number[2]=2; 

Now I have, for example, a row for which ID is 27. How do I get the index of this row? (must be 1)

+4
source share
5 answers

You can use foreach like:

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

Where $ key is the index you need.

+2
source

I do not use Wordpress myself, but I suggest you try the following to find out what happens:

 $sub = $wpdb->get_results("SELECT t.* FROM $wpdb->terms AS t, $wpdb->term_taxonomy AS tt WHERE tt.parent = $termID AND tt.term_id = t.term_id "); $i=-1; foreach ($sub as $key) { print_r($key); } 

This will print out the data that you return from the request, so that you can decide what to do with it. If you are still stuck, post the results here.

+1
source

Your question does not seem to be SQL related. As in SQL, if you already have id (27), you should use this, not the index value.

So, I assume that you are looking for a suitable string in PHP, if it is provided with an id value, possibly by the user. So your question is how to find a record in an unordered array .

  • You can scroll through all the entries until you get a match.
  • You can create an ordered match identifier for the index (e.g. a binary tree)
  • You can create a hash table matching identifier for indexing

The faster the search, the more memory it will use. Which end of the selected spectrum depends on your needs and limitations.

+1
source

Try

 SET @rowId :=0; SELECT @rowId := @rowId + 1 as rowid , fieldName from tableName 
+1
source

You do not need a row index, save it in the database. There is a special flag when you set up the MySQL db structure to automatically grow. It is not possible to get the row index in the database because there are no row indexes, all the data that you see in the database viewer is the result of a search without parameters. If you really need it, you can just get all the data in the table and manually get your row id, as ign said. (Use foreach key and value)

0
source

Source: https://habr.com/ru/post/1390428/


All Articles