我在PHP中创建了两个函数,这个函数返回一个数组,我想要合并数组并返回一个JSON。
示例代码:
// random JS code followed by Google Analytics code
答案 0 :(得分:0)
您可以使用array_merge和json_encode:
执行此类功能function getMergedJson($array1, $array2) {
$result = array_merge($array1, $array2);
return json_encode($result);
}
根据您在评论中向我展示的内容,我认为您应该遵循,与数组合并无关:
function get_data($conn, $post_id) {
$qry = "SELECT * FROM post WHERE Post_id='".$post_id."'";
$res = mysqli_query($conn, $qry);
global $myArray;
if (mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$Post_id = $row['Post_id'];
$Post_title = $row['Post_title'];
$Post_body = $row['Post_body'];
$myArray[] = array( 'Post_id' => $Post_id, 'Post_title' => $Post_title, 'Post_body' => $Post_body, 'Username' => likedislike($conn, $post_id, $myArray); );
}
}
echo json_encode($newarray);
}
function likedislike($conn, $post_id, $myArray)
{
$qry1 = "SELECT * FROM likeunlike WHERE postid = '".$post_id."' AND likes=1";
$res1 = mysqli_query($conn, $qry1);
$count = mysqli_num_rows($res1);
global $myArray;
global $username;
$userlist = array();
while($row = mysqli_fetch_assoc($res1)) {
$Usrname = $row['username'];
$userlist[] = array( 'username' => $Usrname );
}
return $userlist;
}
答案 1 :(得分:0)
使用第一个array_merge();
$result = array_merge($array1, $array2);
http://php.net/manual/en/function.array-merge.php
然后是json_encode
$json = json_encode($result);
答案 2 :(得分:0)
array_merge
array_merge()函数将一个或多个数组合并为一个数组。
<强> json_encode 强>
json_encode()用于转换为json数据
示例:强>
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
$myarray = array_merge($a1,$a2);
$json_data = json_encode($myarray );
echo json_data;
?>
或强>
示例:如果键和值
<?php
$a1=array("Volvo"=>"XC90","BMW"=>"X5");
$a2=array("abc"=>"XxX","xyz"=>"Xz");
$myarray = array_merge($a1,$a2);
$json_data = json_encode($myarray);
echo $json_data;
?>
例如见...... https://eval.in/817282
答案 3 :(得分:0)
$result = array_merge($array1, $array2);
echo json_encode($result);