簡體   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