for循环显示不需要的结果php

时间:2016-10-15 15:00:55

标签: php arrays json for-loop

我创建的php的结果输出如下:

  

{"导致":[{"天":" 1""计数":" 0" }]} {"导致":[{"天":" 2""计数":" 0" }]} ...

但我想要结果的输出:

  

{"导致":[{"天":" 1""计数":" 0" },{"天":" 2""计数":" 0"} ...

以下是我的php代码:

<?php

 define('HOST','xx');
 define('USER','xx');
 define('PASS','xx');
 define('DB','xx');


 //$month = $_POST['month'];
 //$year = $_POST['year'];

 $month = 10;
 $year=2016;


 $con = mysqli_connect(HOST,USER,PASS,DB);

 $sql = "select count(entryID) from Entry where
      EXTRACT(DAY FROM(entryTime)) = '$day'  AND
      EXTRACT(MONTH FROM(entryTime)) = '$month' AND 
      EXTRACT(YEAR FROM(entryTime))= '$year'";

 for($day =1 ; $day<31 ; $day++)
 {
 $day2 = (string)$day;
 $res = mysqli_query($con,$sql);

 $result = array();
 while($row = mysqli_fetch_array($res)){
 array_push($result,
 array('day' =>$day2,
    'count' => $row[0]
 ));

 }

 }
 echo json_encode(array("result"=>$result));


 mysqli_close($con);

 ?>

寻求帮助..

4 个答案:

答案 0 :(得分:2)

第一个错误:您将始终为您执行的每个查询计算0,因为您的字符串$sql在定义过程中包含未定义的变量$day

第二个错误:你在循环中重新声明$result

解决方案:

 $result = array();
 for ($day=1 ; $day<31 ; $day++) {
     $sql = "select count(entryID) from Entry where
         EXTRACT(DAY FROM(entryTime)) = '$day'  AND
         EXTRACT(MONTH FROM(entryTime)) = '$month' AND 
         EXTRACT(YEAR FROM(entryTime))= '$year'";
     $res = mysqli_query($con,$sql);

     $day2 = (string)$day;
     while($row = mysqli_fetch_array($res)) {
         array_push($result,
         array('day' =>$day2,
            'count' => $row[0]
         ));
     }
 }
 echo json_encode(array("result"=>$result));

答案 1 :(得分:0)

问题在于for循环中的result = array(),每次迭代都会再次创建结果数组。尝试在循环之前定义数组。 然后将每个结果合并到单个结果数组中。

ps:很抱歉我无法分享更正的代码,因为我现在的能力有限,但我想这个线索会对你有帮助。

答案 2 :(得分:0)

我认为你需要将defmodule A do defmodule B.C do def test do IO.inspect B end end end > A.B.C.test A.B 从for循环中删除,因为它根本没有任何意义。尝试从那里删除它并将其放在for循环

之前

答案 3 :(得分:0)

尝试在@Configuration public class DBConfig extends HibernateJpaAutoConfiguration { @Value("${spring.jpa.orm}") private String orm; @SuppressWarnings("SpringJavaAutowiringInspection") public DBConfig(DataSource dataSource, JpaProperties jpaProperties, ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider) { super(dataSource, jpaProperties, jtaTransactionManagerProvider); } @Override @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder factoryBuilder) { final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = super.entityManagerFactory(factoryBuilder); entityManagerFactoryBean.setMappingResources(orm); return entityManagerFactoryBean; } } 之前设置$result = array();。您只需在for-loop的每次迭代中重新初始化$result

for-loop