2017-05-19 32 views
0

我学习PHP以及JSON和想不通,为什么我有以下的输出:
JSON结果:JSON给人怪异的输出在PHP

{ 
"Results": [ 
    { 
     "user_id": "1" 
    }, 
    { 
     "email": "[email protected]" 
    }, 
    { 
     "first_name": "User" 
    }, 
    { 
     "last_name": "One" 
    }, 
    { 
     "password": "pass1" 
    }, 
    { 
     "creation_date": null 
    }, 
    { 
     "profile_type": "0" 
    }, 
    { 
     "user_id": "2" 
    }, 
    { 
     "email": "[email protected]" 
    }, 
    { 
     "first_name": "User" 
    }, 
    { 
     "last_name": "Two" 
    }, 
    { 
     "password": "pass2" 
    }, 
    { 
     "creation_date": null 
    }, 
    { 
     "profile_type": "0" 
    } 
] 
} 

PHP:

<?php 
require_once 'config/db.php'; 
$sql = new db(); 
$conn = $sql->connect(); 

$query = isset($_GET['query']) ? mysql_real_escape_string($_GET['query']) : ""; 


if(!empty($query)) 
{ 
    $qur = mysql_query($query); 
    $result = array(); 

    while($r = mysql_fetch_assoc($qur)) 
    { 
     extract($r); 
     foreach($r as $key => $value) 
     { 
      $result[] = array($key => $value); 
     } 
     $json = array("Results" => $result); 
    } 
} 

@mysql_close($conn); 

/* Output header */ 
header('Content-type: application/json'); 
echo json_encode($json, JSON_PRETTY_PRINT); 
?> 

我的问题是,为什么它会将每个值分成新记录,我希望每个MySQL记录都是一个JSON记录。

+0

有没有什么奇怪的,那是你要求的输出 –

+0

你能解释这段代码有什么问题吗? – arti

+0

您正在寻找元素数组。 –

回答

4

只是分配您行$result

while($r = mysql_fetch_assoc($qur)) 
{ 
    $result[] = $r; 
} 
$json = array("Results" => $result); 
+0

为什么downvote @devofash? – FrankerZ

+0

up up弥补不应得的DV –

+0

感谢您的帮助球员:) – arti

1

它这样做是因为你的for循环:

foreach($r as $key => $value) 
{ 
    $result[] = array($key => $value); 
} 

也许你应该尝试对数据像json_encode返回。

http://php.net/manual/en/function.json-encode.php

编辑:

尝试是这样的:

$data = array(); 
while($row = mysqli_fetch_assoc($result)) 
{ 
    $data[] = $row; 
} 
echo json_encode($data, JSON_PRETTY_PRINT); 
+0

'echo json_encode($ json,JSON_PRETTY_PRINT);' –

-3

我不会用MySQL来开始,使用PDO。但是,如果你必须的话,你不需要foreach。下面会做。

while($r = mysqli_fetch_assoc($qur)) 
    { 
     $result[] = $r; 

     $json = array("Results" => $result); 
    } 
+0

完美答案,谢谢! – arti

+0

如果您从另一张海报的帖子启发自己,请给予奖励。另外,尝试做对。 $ json赋值应该在循环之后。 – YvesLeBorg

+1

arti我认为这是你寻找的答案请参阅@ FrankerZ的 [下面的答案](http://stackoverflow.com/questions/44068630/json-giving-weird-output-in-php/44068743#44068743) –