繁体   English   中英

从SQL合并两个结果以在PHP上回显

[英]Merging two results from sql to echo on php

$result = mysql_query("SELECT * FROM election WHERE election_date >= NOW() ORDER BY election_date LIMIT 1");
$result2 = mysql_query("SELECT has_voted from users where pid = 3");

$results = array();
$line1 = mysql_fetch_object($result2);
while($line = mysql_fetch_array($result, MYSQL_ASSOC)){
    $results[] = $line;
}

array_push($results, $line1);
echo (json_encode($results));

那就是我的php代码,我在这里想要输出的是两个sql结果。 下面是我在回显结果时将得到的输出。

[
{
election_id: "3",
election_title: "",
election_date: "2016/02/20",
start_time: "08:00",
end_time: "23:59",
election_venue: "",
status: "0",
num_needed: "3"
},
{
has_voted: "1"
}
]

如您所见, has_voted: "1"与第一个分开。 我有可能将该结果包含在第一个结果中吗? 所以我想要的输出是这样的:

[
{
election_id: "3",
election_title: "",
election_date: "2016/02/20",
start_time: "08:00",
end_time: "23:59",
election_venue: "",
status: "0",
num_needed: "3"
has_voted: "1"
}
]

我尝试使用array_merge(),这是我的代码:

$result = mysql_query("SELECT * FROM election WHERE election_date >= NOW() ORDER BY election_date LIMIT 1"); $result2 = mysql_query("SELECT has_voted from users where pid = 3");

$results = array(); $results1 = array();

while($line = mysql_fetch_array($result, MYSQL_ASSOC)){ $results[] = $line; } while($line1 = mysql_fetch_array($result2, MYSQL_ASSOC)){ $results1[] = $line1; }`

$final = array_merge($results, $results1); echo (json_encode($final));

输出仍然不是我想要的输出:

[ { election_id: "3", election_title: "", election_date: "2016/02/20", start_time: "08:00", end_time: "23:59", election_venue: "", status: "0", num_needed: "3" }, { has_voted: "1" } ]

使用array_merge()

$finalArr = array_merge($results, $line1);
echo json_encode($finalArr);

我们可以使用array_merge($line,$line1); 然后输出将是

Array ( [election_id] => 3 [election_title] => [election_date] => 2016/02/20 [start_time] => 08:00 [end_time] => 23:59 [election_venue] => [status] => 0 [num_needed] => 3 [has_voted] => 1 ) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM