SQL行列转换的问题

WBOY
Release: 2016-06-23 14:05:23
Original
807 people have browsed it

表结构

ID  KEY  VAL
1   sex  male
2   day  365  
4   num  12345

现在我想在这个页面 echo $a['sex'] 就显示 male  echo $a['day']  就显示  365

PHP查询mysql语句要怎么写方便随时echo呢?   


回复讨论(解决方案)

    前略    function select_db_col ($sql_string)    {    	unset($this->records);    	@mysql_free_result($this->result);    	$this->result=@mysql_query($sql_string,$this->db);			$i=1;			while($temp_rows=@mysql_fetch_array($this->result, MYSQL_ASSOC))			{				for ($j=0;$j<count($temp_rows);$j++)				{					$temp_key_name = mysql_field_name($this->result, $j);					$this->records["$temp_key_name"][$i] = $temp_rows["$temp_key_name"];				}				$i++;			}    	return $this->records;    }
Copy after login

这样写就是按列输出了,格式为$var[列][行]
然后
$a=array_combine($var['KEY'], $var['VAL']);
Copy after login

要在 mysql 中实现,需要书写存储过程
你搜索“交叉表”,就可以找到多个版本的实现算法

如果用 php 实现,可以在读取查询结果时构造
while($row = mysql_fetch_assoc($rs)) {
  $a[$row['key']] = $row['val'];
}

二楼威武,这么复杂的问题一行代码搞定。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template