I have a MySQL SELECT
query (using wpdb_custom->get_results()
) that returns two UNSIGNED
TINYINT
columns Col_1
and Col_2
for an arbitrary number of rows. What is the least costly way in PHP to lookup the value of Col_2
from the recordset given a value of Col_1
?
Emp_ID Col_1 Col_2
120 3 11
120 5 17
120 6 8
120 8 13
120 11 10
So for example, the pseudo-code lookup function lookup(6, $recordset)
would yield 8
.
Let's assume your recordset to array will look something like this :
Array
(
[0] => Array
(
[Emp_ID] => 120
[Col_1] => 3
[Col_2] => 11
)
[1] => Array
(
[Emp_ID] => 120
[Col_1] => 5
[Col_2] => 17
)
[2] => Array
(
[Emp_ID] => 120
[Col_1] => 6
[Col_2] => 8
)
....
)
Now create ONCE per page a search array.
$search_array =array();
foreach( $recordSet as $key=>$data ){
$search_array[$data['Col_1']]=$data['Col_2'];
}
Then each time you need to find the value of Col_2 from Col_1 just use :
echo $search_array[6]; // will return 8
For the other way around with the same search array use array_search()
echo array_search("8",$search_array); // will return 6