【问题标题】:Trim An json Array via PHP通过 PHP 修剪一个 json 数组
【发布时间】:2017-02-16 08:23:08
【问题描述】:

如何修剪这个数组?我想回显我数组的第一个对象,即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);
?>

请看一下这张照片中的输出

【问题讨论】:

  • print_r($id) 和有问题的推杆
  • 不正确,给我Array ( [0] =&gt; 26 [1] =&gt; 30 [2] =&gt; 31 [3] =&gt; 32 [4] =&gt; 33 ) Array ( [0] =&gt; 26 [1] =&gt; 30 [2] =&gt; 31 [3] =&gt; 32 [4] =&gt; 33 [5] =&gt; 40 [6] =&gt; 30 [7] =&gt; 31 [8] =&gt; 32 [9] =&gt; 33 ) Array ( [0] =&gt; 26 [1] =&gt; 30 [2] =&gt; 31 [3] =&gt; 32 [4] =&gt; 33 [5] =&gt; 40 [6] =&gt; 30 [7] =&gt; 31 [8] =&gt; 32 [9] =&gt; 33 [10] =&gt; 100 [11] =&gt; 200 [12] =&gt; 300 [13] =&gt; 400 )
  • implode() 是错误的使用方式。

标签: php arrays json object


【解决方案1】:

你需要重新初始化 $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);
?>

【讨论】:

  • 这里有什么变化?
  • Yessssssss,感谢它。
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多