我正在我的php脚本中执行多个“select”语句。然后我按$Output=array($out, $out1);
将它们添加到数组中,然后按json_encode()
输出格式为[ [{},{}] , [{}, {}] ]
如何在表单中转换它 - {"str1": [{},{}], "str2": [{},{}]}
php脚本:
<?php
require 'DbConnect.php';
$query = ("SELECT * FROM `cars`");
$query1 = ("SELECT * FROM `City`");
if ($query_run = mysql_query($query)){
while ($query_row = mysql_fetch_assoc($query_run)){
$out [] = $query_row;
}
}else{
echo 'Fail';
}
//second query
if ($query_run1 = mysql_query($query1)){
while ($query_row1 = mysql_fetch_assoc($query_run1)){
$out1 [] = $query_row1;
}
}else{
echo 'Fail';
}
$Output=array($out, $out1);
echo(json_encode($Output));
?>
答案 0 :(得分:1)
如果您的结果是[ [{},{}] , [{}, {}] ]
然后尝试
$Output=array('str1'=>$out,'str2'=>$out1);
echo(json_encode($Output,JSON_FORCE_OBJECT));
答案 1 :(得分:0)
试试这个
$query = "SELECT
post_title,
guid
FROM testwp_posts
WHERE
post_author = $user_id
AND
post_status = 'publish'
ORDER BY ID DESC LIMIT $number_of_posts";
$result = mysql_query($query) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
答案 2 :(得分:0)
<?php
require 'DbConnect.php';
$query = ("SELECT * FROM `cars`");
$query1 = ("SELECT * FROM `City`");
if ($query_run = mysql_query($query))
{
while ($query_row = mysql_fetch_assoc($query_run))
{
$output['cars'][] = $query_row;
}
}
else
{
echo 'Fail';
}
//second query
if ($query_run1 = mysql_query($query1))
{
while ($query_row1 = mysql_fetch_assoc($query_run1))
{
$output['city'][] = $query_row1;
}
}
else
{
echo 'Fail';
}
echo(json_encode($output));
?>
可能有帮助
答案 3 :(得分:0)
我不确定这是否有助于您的要求,但请尝试以下事项..
而不是使用
$out [] = $query_row;
使用
$out['str1'][] = $query_row;
而不是
$out1 [] = $query_row1;
使用
$out['str2'][] = $query_row1;
现在试试这个
echo(json_encode($out));