[英]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));
That is my php code, what I want here is to output the two sql results as one. 那就是我的php代码,我在这里想要输出的是两个sql结果。 Below is the output that I will get when echoing the result. 下面是我在回显结果时将得到的输出。
[
{
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"
}
]
As you can see, the has_voted: "1"
is separated from the first one. 如您所见, has_voted: "1"
与第一个分开。 Is it possible for me to include that result to the first one? 我有可能将该结果包含在第一个结果中吗? So the output that I want is this: 所以我想要的输出是这样的:
[
{
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"
}
]
I have tried using the array_merge() and this is my code: 我尝试使用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));
The output is still not the one I wanted: 输出仍然不是我想要的输出:
[ { 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" } ]
Use array_merge() : 使用array_merge() :
$finalArr = array_merge($results, $line1);
echo json_encode($finalArr);
We can use array_merge($line,$line1);
我们可以使用array_merge($line,$line1);
Then output will be 然后输出将是
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.