如何在PHP中将查询结果导入数组

时间:2013-12-24 06:44:29

标签: php arrays

我在数据库上写了一个查询,结果以这种形式给出

Apples-100
Grapes-200
Oranges-50
Bananas-30

现在我需要将数据存储在像这样的数组中

[['Apples',100],['Grapes',200],['Oranges',50],['Bananas',30]]

我怎么能实现这一点我试过这个

while($row = mysql_fetch_assoc($getdatagraoh)){ 
    $plotgraphs[] = array(
        $row['Compliancestatus'],
        $row['value']
    );
}
header('ContentType: application/json; charset=utf-8');
$data= json_encode($plotgraphs);

我无法实现这一点。请在这方面帮助我。

5 个答案:

答案 0 :(得分:2)

首先不要使用mysql_ *作为其删除,而是使用mysqli_ *或PDO

$plotgraphs中存储值后,回到您的问题,然后像这样爆炸,您将获得所需的结果

foreach ( $array as $k => $v ) {
    $seprated = explode ( '-', $v );

    //echo '<pre>';
    //print_r ( $seprated );
    echo json_encode(( $seprated ));
}

输出

["Apples","100"]["Grapes","200"]["Oranges","50"]["Bananas","30"]

答案 1 :(得分:1)

while($row = mysql_fetch_assoc($getdatagraoh)){ 
  $plotgraphs[] =$row;
}

旁注:Why shouldn't I use mysql_* functions in PHP?

答案 2 :(得分:0)

试试这个:

<?php
$plotgraphs = array();

while($row = mysql_fetch_assoc($getdatagraoh)){ 
    $plotgraphs[] = $row;
}
?>

$row数组已分配给$plotgraphs

答案 3 :(得分:0)

var $plotgraphs = [];  
  while( $row = mysql_fetch_assoc( $getdatagraoh)){
        $plotgraphs[] = $row; // Inside while loop
        //or
        $plotgraphs[ $row['id']] = $row;
    }

答案 4 :(得分:0)

试试这样: 既然您有更改问题,可以试试这个:

$arrayName = array('Apples-100','Grapes-200','Oranges-50','Bananas-30');



foreach($arrayName as $value)
{
     $plotgraphs = explode("-",$value);
   echo  json_encode( $plotgraphs);
}
  

输出:[“苹果”,“100”] [“葡萄”,“200”] [“橘子”,“50”] [“香蕉”,“30”]

OR

foreach($arrayName as $value)
{
     $plotgraphs[] = explode("-",$value);

}
echo json_encode( $plotgraphs);