如何从单个数组中的两个查询中传递 json

Posted

技术标签:

【中文标题】如何从单个数组中的两个查询中传递 json【英文标题】:how to pass json from two query in single array 【发布时间】:2018-01-25 07:10:42 【问题描述】:

$sql = "SELECT user_registration.user_id, user_registration.full_name, user_registration.username, user_profile.profile_picture FROM user_registration LEFT JOIN user_profile ON user_registration.user_id = user_profile.user_id ";

    $result = $con->query($sql);

    if ($result->num_rows > 0) 

    while($row = $result->fetch_assoc()) 
            $outaa[] = $row;

            $f_user_id = $row['user_id'];

        $sql1 = "SELECT status FROM user_follower WHERE (from_user_id = '$f_user_id' AND to_user_id = '$user_id' ) OR (from_user_id = '$user_id' AND to_user_id = '$f_user_id' )";

        $result1 = $con->query($sql1);
        if ($result1->num_rows > 0) 
        while($row1 = $result1->fetch_assoc()) 

            $outaa[] = $row1;
         
        
        else 
            $outaa[] =  "No";
           

    
    
   $out = array_merge(array('result'=>'true','reason'=>'Data Fetching Succesfully','user_suggested_data' => $outaa));     

我想传入单个数组。

像这样的回答:

"user_suggested_data": “0”: "user_id": "121", "full_name": "Ankit Shah", “用户名”:“shah_ankit39”, “profile_picture”:空, “状态”:0 , “1”: "user_id": "122", "full_name": "pooja", “用户名”:“pooja25”, “profile_picture”:空, “状态”:0 , “2”: "user_id": "123", "full_name": "swapnil", “用户名”:“swapnil25”, “profile_picture”:空, “状态”:0 ,


【问题讨论】:

【参考方案1】:

您可以通过将 SQL 查询改进为:

  SELECT
    user_registration.user_id,
    user_registration.full_name,
    user_registration.username,
    user_profile.profile_picture,
    user_follower.status
  FROM
    user_registration LEFT JOIN user_profile USING(user_id)
  WHERE
    (user_follower.to_user_id = '$user_id'
      AND user_follower.from_user_id = user_registration.user_id)
    OR (user_follower.from_user_id = '$user_id'
      AND user_follower.to_user_id = user_registration.user_id)"

将其作为字符串存储在$sql 变量中,最后执行查询:

$result = $con->query($sql);

【讨论】:

以上是关于如何从单个数组中的两个查询中传递 json的主要内容,如果未能解决你的问题,请参考以下文章

SQL 如何从单个列中的所有值创建 JSON 数组

如何在单个查询中返回 node.js mysql 中的嵌套 json

Gatsby:如何将多个上下文 ID 传递给单个查询?

过滤从查询参数传递的数组。 NestJS,TypeORM

如何从sql server中的表中查询json数组类型列的值?

使用 JSON 将数据从 PHP 数组传递到 Highcharts 图表