如何将选择查询与水平查找组合在一起

I am using the following code:

//Add Template Documentation
$sql = "SELECT doctype, templatename FROM templates_documents WHERE scope = '".$values["msscope"]."'";
$rs = CustomQuery($sql); 
$results = $rs;
while ($row = $results->fetch_assoc())
{
$sql2 = "INSERT INTO documents_doucments (companyfk, doctype, doctitle) values('".$values["companypk"]."','$row[doctype]','$row[templatename]')";CustomQuery($sql2);
}  

Which works absolutely fine, and inserts a set of template documents into the clients document table depending on what product they purchase.

I need to modify this code slightly to add what I can only describe as a HLookup feature from excel. In the output table (documents_doucmentS) I need to add a docref field, this can come from 1 of 7 columns in the source table (templates_documents), i.e.

9001ref, 14001ref, 18001ref, 914001ref, 918004rev, 1418001ref, and 91418001 ref

In the source table there is a field called 'scope' which again has 7 possibilities:

9001 14001 18001 9001,14001 9001,18001 14001,18001 9001,14001,18001

I need to add a line in the code that if scope='9001' $docref=9001ref, elseif scope '14001' $docref=14001ref, etc, etc for each of the 7 variants, so that the docref depends on what the scope is.

First question, can someone please start me off on that code, one or two examples will be enough to get me going.

Secondly, where do I put it within the code I already have, within the query, or within the loop?

Many thanks in advance