
正文
php数据库转数组,php 输出数组
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
PHP 去读数据库到数组 怎么弄
本文实例讲述了php实现通用的从数据库表读取数据到数组的函数。分享给大家供大家参考。具体分析如下:
此函数不关心表结构,只需要指定表名、结构和查询条件既可以对表进行通用查询操作,非常实用。
function listmytablerows($table, $name, $field, $where, $textID) { / / Connect to the database and query execution connect (); $Sql = "select * from". $table. "". $where. "ORDER BY". $field; $Req = mysql_query($sql); $Res = mysql_num_rows($req); ? Select name = "?php echo $name; ?" id="?php echo $textID; ?" option value="" ____/ option ? Php / / We do a loop that will read the information for each record while ($data = mysql_fetch_array($res)) { / / We display the information from the current record ? Option value = "?php echo $data['id']; ?" ?php echo $data[$field]; ? / Option ? Php } ? / Select ? Php } ?
相关问答
Q1: php如何将数据库查询统计出来的数据,转换成为自己想要的格式数组?
我也很就纠结这个问题,现在我是这样做的
$res = mysqli_query ($sql, "select BCur from microvast where id between 1 and 50");
foreach($res as $x=$x_value) {
foreach($x_value as $k=$v) {
$data[] = $v;
}
这样可以$data[]生成了‘BCur’一列的一个索引数组,但是执行效率不高,多列就要做多次查询,期待更好的方法。
while ($row=mysqli_fetch_assoc($res)){
$id=$row["id"];
......
echo $id;
}
这个办法只能打印出来
Q2: php如何把数据库里一列的值看成是一个数组然后输出
使用eval转换,例子代码:
?php $str="array ( 0 = array ( 'a' = '11', 'b' = '111', ), 1 = array ( 'a' = '22', 'b' = '222', ), 2 = array ( 'a' = '33', 'b' = '333', ), );"; $str=preg_replace('/,\s+\)/',')',$str);//删除括号前多余的逗号,不符合语法 eval('$arr='.$str);//转换为数组 print_r($arr);//输出数组?
Q3: 怎么把php查询数据库内容变成数组
?php
$arr = array();
$query = mysql_query($sql);
while($row=mysql_fetch_assoc($query))
{
$arr[]=$row;
}
?
此时 $arr 应该是一个二维数组
Q4: php有什么函数能够直接转换数组?
因为不支持代码标签了,上面放图,下面是代码
php API 中没有可以直接打到效果的函数,在此封装了一个
下面是代码
代码部分
?php
/**
* $list 数组
* $column_num 数据列数量
*/
function groupBy($list, $column_num){
$group = [];
$keys = array_keys($list);
for ($i=0; $i$column_num; $i++){
$item = [];
foreach ($keys as $key){
$item[$key] = $list[$key][$i];
}
$group[] = $item;
}
return $group;
}
$temp = [
'bg' = ['bg1','bg2','bg3'],
'img' = ['img1','img2','img3'],
'url' = ['url1','url2','url3'],
];
$list = groupBy($temp,3);
echo(json_encode($list));
?






