通过PHP修剪json数组

时间:2017-02-16 08:23:09

标签: php arrays json object

如何修剪此阵列?我想要回显我的数组的第一个对象,即id,我的意思是id的第3行

 <?php
    $con=mysqli_connect("localhost","root","","arrayy");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
 $sql="SELECT `survey_answers` FROM `user_survey_start`";

if ($result=mysqli_query($con,$sql)){

 while ($row = mysqli_fetch_row($result)){

    $json = $row[0];
    $jason_array  = json_decode($json,true);
    foreach ($jason_array as $data){
        $id[] = $data['id'];
        //$answer[] = $data['answer'];
      // $type[] = $data['type'];

        // here code to insert/update values to db column
    }

    echo implode(',',$id)."</br>";
   // echo implode(',',$answer);
  //  echo implode (',',$type);
  }

}
mysqli_close($con);
?>

请查看此照片中的输出 My Output

1 个答案:

答案 0 :(得分:2)

您需要重新初始化$ id数组。试试这个

<?php
    $con=mysqli_connect("localhost","root","","arrayy");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
 $sql="SELECT `survey_answers` FROM `user_survey_start`";

if ($result=mysqli_query($con,$sql)){

 while ($row = mysqli_fetch_row($result)){

    $json = $row[0];
    $jason_array  = json_decode($json,true);
    $id = array();
    foreach ($jason_array as $data){
        $id[] = $data['id'];
        //$answer[] = $data['answer'];
      // $type[] = $data['type'];

        // here code to insert/update values to db column
    }

    echo implode(',',$id)."</br>";
   // echo implode(',',$answer);
  //  echo implode (',',$type);
  }

}
mysqli_close($con);
?>