如何在PHP中使用MySQL创建自定义JSON布局

时间:2013-01-10 13:23:02

标签: php mysql json

我在PHP中有一个MySQL查询,可以返回两列结果

第一栏是标签 第二列是价值

我已阅读http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP但我很难理解如何在MySQL中使用PHP执行以下JSON

[
  {
    key: "Cumulative Return",
    values: [
      { 
        "label": "One",
        "value" : 29.765957771107
      } , 
      { 
        "label": "Two",
        "value" : 0
      } , 
      { 
        "label": "Three",
        "value" : 32.807804682612
      } , 
      { 
        "label": "Four",
        "value" : 196.45946739256
      } , 
      { 
        "label": "Five",
        "value" : 0.19434030906893
      } , 
      { 
        "label": "Six",
        "value" : 98.079782601442
      } , 
      { 
        "label": "Seven",
        "value" : 13.925743130903
      } , 
      { 
        "label": "Eight",
        "value" : 5.1387322875705
      }
    ]
  }
]

我可以手动编写循环来输出原始文本以形成如上所述的JSON,但我真的想使用 json_encode

<?php
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);

    $query = "select label, value from table";

    $stmt = $dbh->prepare($query);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($result)) {
        echo '[
        {
          key: "Cumulative Return",
          values: [';

        for ($row = 0; $row < count($result); $row++) {
            echo "{";
            echo '"label": "' . $result[$row]['Label'] . '",';
            echo '"Value": ' . $result[$row]['Value'];
            echo "},";
            echo '       ]
      }
    ]';
        }

    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

?> 

可以这样做吗?如果是这样的话?

6 个答案:

答案 0 :(得分:4)

使用json_encode()

$jsonArr = array( 'key' => 'Cumulative Return' , 'values' => array() );


foreach ($result as $res) 
{
   $jsonArr['values'][] = array('label'=>$res['Label'],'value'=>$res['value']);

}

echo json_encode($jsonArr);

答案 1 :(得分:3)

试试这个:

$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);

    $query = "select label, value from table";

    $stmt = $dbh->prepare($query);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $values = array();

    for($row = 0; $row < count($result); $row++)
    {
        $values[] = array('label' => $result[$row]['Label'], 'value' => $result[$row]['Value']);
    }

    $to_encode = array(
                        array('key' => 'Cumulative Return', 
                              'values' => $values;
                              )
                        );
    echo json_encode($to_encode);

} catch (PDOException $e) {
    echo $e->getMessage();
}

答案 2 :(得分:2)

您只需要以您希望将其转换为json的方式创建数组:

$encode = array(
    'key' => 'Cumulative Return', 
    'values' => $result->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($encode);

这应该是你要求的。

答案 3 :(得分:1)

这是JSON的用处 - 你不需要费心去手动编码。

$json = array();
$results = array();
$json['key'] = 'Cumulative return';

foreach ($row as $entry) {
    $results['label'] = $entry['Label'];
    $results['value'] = $entry['Value'];
    $json['value'][] = $results;
}

echo json_encode($json);

就是这样。享受!

答案 4 :(得分:0)

我使用代码点火器

这就是我如何根据数据库中的值创建自定义json,希望它有所帮助

&#13;
&#13;
function getData() {

		$query = $this -> db -> get('gcm_users');
		
		$result_array=array();

		if ($query -> num_rows() > 0) {
			
			$results=$query->result();

			foreach ( $results as $row) {
				
				$data=array();
				
				$data['name']=$row->name;
				$data['email']=$row->email;
				
				array_push($result_array,$data)	;		
			}

			

			return json_encode($result_array);

		} else {

			echo "something went wrong";

		}
	}
&#13;
&#13;
&#13;

这是我从db中恢复数据的功能,因为即时通讯使用像Code igniter这样的框架工作我不必担心我的其他sql操作希望你能从这段代码中提取你需要的东西..

输出就像这样

&#13;
&#13;
[{"name":"allu","email":"allu@gmail.com"},{"name":"ameeen","email":"cdfdfd@gmail.com"}]
&#13;
&#13;
&#13;

答案 5 :(得分:0)

我构建了一个简单的函数(我更喜欢使用它,而不是json_encode-因为我对所获取的数据拥有完全控制权):

    public function mysqlToJoson($mysqlarray)
    {
        $json_string = "[";

        while ($array = $mysqlarray->fetch()) {
            $i = 1;
            if ($json_string != "["){$json_string .= ",";}
            foreach ($array as $key => $value) {
                if ($i == 1) {
                    $json_string .= '{"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
                } else $json_string .= ',"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
                $i++;
            }
            $json_string .= '}';
        }
        $json_string .= ']';
        return $json_string;
    }