热搜:NVER node 开发 php

如何生成数组

2024-09-21 18:00:01
如何生成数组

在mysql库中一个表中有这样两个字段,$cont_type,$cont_id,并且各自的记录数都超过一条,如何生成这样一个2维数组呢$tarTree[$cont_type][]=$cont_id;用mysql_fetch_row()吗


回复讨论(解决方案)

//读取出来之后,生成为二维数组即可,直接贴示例代码<?PHP	$conn = mysql_connect("localhost", 'root', ''); //如果有密码可以加上          $tarTree = array();	if($conn)	{			if(mysql_select_db('sql_primary', $conn)) //sql_primary是你的数据库名		{			$sql = "SELECT * FROM customers";//customers替换为你的表即可			$result = mysql_query($sql);			while($row = mysql_fetch_array($result))			{				//echo $row['company']."\r\n";                                $tarTree[$row['cont_type']][]=$row['cont_id'];			}			mysql_close($conn);		}	}?>

实现思路
1.一行一行读取数据
2.每次读取一行数据,将$row['cont_type']以key传递给$tarTree,$row['cont_id']作为键值传递给该二维数组即可。

很经典的例子,在YII中同样适用