如何打印json数组进行解码?

时间:2014-05-03 19:59:07

标签: php mysql json

我正在学习JSON。

getDatas.php 内容:

$query = "SELECT domain FROM access WHERE userid = '".$userid."'";
$result = mysql_query($query) or die(mysql_error());

$res = array();
while($row = mysql_fetch_array($result)){

    $query2 = "SELECT COUNT(*) as cnt from clients WHERE domain ='".$row['domain']."'";
    $res2   = mysql_query($query2) or die(mysql_error());
    $res2   = mysql_fetch_array($res2);

    $res[] = array('domain' => $row['domain'], 'count' => $res2['cnt']);
};
echo json_encode($res);

输出结果为:

[{"domain":"www.domain1.com","count":"2"},{"domain":"www.domain2.com","count":"42"},{"domain":"www.domain3.com","count":"61"}] 

我如何以这样的方式打印?

我如何干净?

www.domain1.com - 2
www.domain2.com - 42
www.domain3.com - 61

2 个答案:

答案 0 :(得分:0)

试试这个:

$query = "SELECT a.domain, COUNT(c.domain) as cnt
FROM `access` as a
LEFT JOIN `clients` as c on c.domain = a.domain
WHERE a.userid = '".$userid."'
GROUP BY c.domain";
$result = mysql_query($query) or die(mysql_error());

$res = array();
while($row = mysql_fetch_array($result)){
    $res[] = array($row['domain'] => $row['cnt']);
};
echo json_encode($res);

答案 1 :(得分:-1)

你只需要使用

echo json_encode($res);