PHP数组到JSON字符串转换

时间:2018-06-21 07:22:13

标签: php arrays json

大家好,我是编程新手,我的担心如下。  我有以下php代码,用于计算学生的平均值,并将结果填充到关联数组中。稍后应将此数组转换为json格式。

    require_once("functions.inc"); // all my functions are here

   $conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DB); // connects to my database
if (!$conn) {
error_log("Cannot connect to MySQL: " .$mysqli->connect_error);
return false;
}

         $query = "SELECT distinct exam.student_matricule from exam join student on exam.student_matricule=student.student_matricule where student.class_id=3"; //
          $result=mysqli_query($conn,$query);
           if(false===$result)
           {    
              printf("error: %s \n",mysqli_error($conn));
           }

           while($row= $result->fetch_assoc()) 
           {
            $studentmatricule = $row['student_matricule'];

            $average=student_average(3,$studentmatricule,1); // this function call calculates students' averages

            $stud_averages[$studentmatricule]=$average; //associative array that has **$studentmatricule** as key and **$average** as value

          }

           foreach($stud_averages as $student => $av)
           {
            $data=array('student_matricule'=>"$student",'average'=>"$av");
            print json_encode($data);
           }

我现在担心的是,打印json_encode($ data)打印

{“ student_matricule”:“ 17A002NA”,“ average”:“ 12.52”} {“ student_matricule”:“ 17A001NA”,“ average”:“ 10.53”} {“ student_matricule”:“ 17A003NA”,“平均”:“ 12.69”}

但是我想要类似的东西

[{“ student_matricule”:“ 17A002NA”,“ average”:“ 12.52”},{“ student_matricule”:“ 17A001NA”,“ average”:“ 10.53”},{“ student_matricule”:“ 17A003NA “,” average“:” 12.69“}]

请问我该怎么办? 预先感谢!

3 个答案:

答案 0 :(得分:3)

您正在循环内打印一维数组,因此它作为JSON打印

如果要将其作为JSON数组,则需要将其存储在这样的多维数组中

$data = [];
foreach($stud_averages as $student => $av)
{
   $data[]=array('student_matricule'=>"$student",'average'=>"$av");
}
print json_encode($data); // It prints JSON Array

答案 1 :(得分:0)

您正在foreach循环中分别打印每个数组。您需要将每个循环数据添加到在循环外部定义的数组中。您可以这样尝试:

Supplier<Dialog> oneActionDialog = new Supplier<Dialog>() {
        @Override
        public Dialog get() {
            AcceptDenyDialog oneActionDialog =
                    new AcceptDenyDialog(WearBaseActivity.this);
            oneActionDialog.setTitle("title");
            oneActionDialog.setMessage("message");
            oneActionDialog.setPositiveButton(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Add code here for onClick functionality.
                }
            });
            return oneActionDialog;
        }
    };
oneActionDialog.get().show();

答案 2 :(得分:0)

您也可以这样尝试

$data = [];
$std = array();
foreach($stud_averages as $student => $av)
{
   $std['student_matricule']= "$student";
   $std['average'] ="$av";
}
 array_push($data,$std);
print json_encode($data); // It prints JSON Array