循环:PHP数组通过数据库查询环路输出结果(Looping : PhP Array Loops through Database query to output result)...

深碍√TFBOYSˉ_ 2023-09-24 08:16 133阅读 0赞

  I have an array called $helloArray which looks like

  [peach]=> 1

  [banana]=> 1

  [apple]=> 1

  [pineapple]=> 1

  [grapefruit]=> 2

  [tomatoe]=> 2

  [giger]=> 1

  [watermelon]=> 1

  Database columns look like

  City peach banana apple pineapple grapfruit tomatoe ginger watermelon

  Tokyo 0 0 0 500 0 0 0 0

  DC 50 55 0 0 0 0 0 0

  NY 0 0 0 0 0 500 0 0

  Rome 0 0 0 0 90 0 0 0

  SQL Statment that I used

  $sql=”SELECT peach,banana,apple,pineapple,grapfruit,tomatoe,ginger,watermelon”;

  $sql .=” FROM TestTable2”;

  $sql .=” WHERE city=’NY’”;

  Question:

  How do I loop through the array and then the variable names (aka column names) names so that

  so that we get NY and Rome values of 2 and 1 for the rest. Below is my code that I have tried, not to mention it not working

  foreach ($helloArray as $key=>$value){

  for($i=0;$i<=odbc_num_fields($connection);$i++)

  { if (odbc_result($connection,$i) > 0) {

  echo $value; }

  }

  }

  盾畳圭宛

  OKay, not sure if I completely understand your question without an output sample, but I’m guessing you want:

  Tokyo=> 1

  DC=> 1

  NY=> 2

  Rome=> 2

  If so, your approach is wrong. Don’t pull data and then massage it, construct your SQL to return the data you want.

  SELECT City, CASE WHEN grapefruit > 0 THEN 2 WHEN tomatoe > 0 THEN 2 WHEN peach > 0 THEN 1 WHEN banana > 0 THEN 1 WHEN …

  If it has to be data driven then sort your hello array by descending values and then use it to generate the SQL case conditions and return vals

  — edit —

  Okay, but the code sample above, you are looping through your array as key=>value pairs. So first pass, you’re on peach=>1, then you loop through every column in the return result (peach, watermelon, etc) and check it’s value is greater than 0 and if it is then you output value from your array. (peach=1)

  Because there is no comparison between the fieldname and the key of the array, you are simply going to output 1 for each column while on peach, 1 for each column while on banana, etc. While I am assuming you are wanting to check if the field NAMED peach is greater than zero and if so, then output 1, and if the field named watermelon is greater than zero then output 2, you need to modify your loop. Drop the odbc_num_field and use the odbc_result syntax to specify the column name you want to retrieve. odbc_result($connection, $key) > 0.

  But going by your original question it sounds like that isn’t really what you are looking for, but instead want a city assigned a certain value based on the largest number returned by those field comparisons described above (NY=2) in which case my original answer stands and you just need to use SQL to return that value for each city.

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读