如何在不重复数据的情况下加入2表

时间:2015-07-22 04:41:01

标签: php arrays database multidimensional-array

我需要以下帮助,

我想将其编码

  Array ( [0] => 1 [duration] => 1 [1] => Singapore [ai_Name] => Singapore )
  {"duration":"1","ai_Name":"Singapore"}

但我得到了这个

   Array ( [0] => 1 [duration] => 1 [1] => Singapore [ai_Name] => Singapore )
  {"0":"1","duration":"1","1":"Singapore","ai_Name":"Singapore"}

下面是我的代码



<?php
      require 'dbfunction.php';
      $id = $_GET['staffid'];
      $con = getDBConnect();
			
        if(!mysqli_connect_errno($con)){
            $sqlQueryStr =  "SELECT r.duration, a.ai_Name " .
                            "FROM report r " .
                            "JOIN academicinstitution a ON r.ai_Id = a.ai_Id " .
                            "WHERE staff_Id = '$id' ";

            $result = mysqli_query($con,$sqlQueryStr);
            $row = mysqli_fetch_array($result);
            mysqli_close($con);
      } else {
         echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

        print_r($row);
        echo '<br>';
        $json = json_encode($row);
        echo $json;
    ?>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

尝试使用GROUP BY

此处有更多信息:https://dev.mysql.com/doc/refman/5.1/en/group-by-handling.html

答案 1 :(得分:0)

问题是你得到一个混合数组,一个索引和一个关联数组。使用mysqli_fetch_assoc()代替mysqli_fetch_array()

$result = mysqli_query($con, $sqlQueryStr);
$row = mysqli_fetch_assoc($result);
var_dump($row);

将返回

Array ( [duration] => 1 [ai_Name] => Singapore )

将被解析为

{"duration":"1","ai_Name":"Singapore"}