2

我在 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();
}

?> 

这可以做到吗?如果是这样怎么办?

4

6 回答 6

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);
于 2013-01-10T13:32:22.413 回答
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();
}
于 2013-01-10T13:32:57.793 回答
2

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

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

这应该是您所要求的。

于 2013-01-10T13:29:10.727 回答
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);

就是这样。享受!

于 2013-01-10T13:31:37.630 回答
0

我正在使用代码点火器

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

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";

		}
	}

这是我从数据库中检索数据的函数,因为我使用了诸如代码点火器之类的框架,我不必担心我的其他 sql 操作希望您可以从此代码中提取所需的内容..

输出是这样的

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

于 2015-03-03T05:14:59.017 回答
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;
    }
于 2020-06-17T10:29:28.257 回答