php pdo foreach [英] Php pdo foreach

查看:189
本文介绍了php pdo foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有php pdo函数来从数据库获取json

Here I have php pdo function to get json from database

try {
      $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

     $result = $conn->prepare("SELECT id_tabele,naziv FROM track_aktivnosti WHERE prvi=:prvi AND id_akt=:id_akt AND tabela=:tabela");
     $result->execute(array(':prvi' => $_POST['prvi'], ':id_akt' => $_POST['id_akt'], ':tabela' => $_POST['tabela']));
    $result = $result->fetchAll(); 

          foreach($result as $r) {
          $temp = array();
          $temp[] = array('id' => (int) $r['id_tabele'], 'ime_prezime' => (string) $r['naziv']); 

        }
    $table = $temp;
    $jsonTable = json_encode($table);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;

但是我只得到一个结果,json中的一个元素,等等.

but I get just one result, one element in json etc.

[{"id":1,"ime_prezime":"Pera Peric"}] 

我无法获得的其他元素.为什么?

other element I can't get. WHY?

我必须像这样获取json:

I must get json like this:

[{"id":1,"ime_prezime":"Pera Peric"},[{"id":2,"ime_prezime":"Laza Lazic"}] ] 

但是我只有1.st元素,而其他却没有...

but I get only 1.st element and other not ...

推荐答案

您将在每次迭代中覆盖foreach中的数组.从本质上讲,这意味着在每次迭代时都将清空该数组.该数组将仅包含上次迭代中的值.将$temp = array();声明移到循环外以解决此问题:

You are overwriting the array inside the foreach on each iteration. This essentially means that the array is emptied on each iteration. The array will only contain the values from the last iteration. Move the $temp = array(); declaration outside the loop to fix this:

$temp = array(); // intialize the array

foreach($result as $r) {
    $temp[] = array(
        'id' => (int) $r['id_tabele'], 
        'ime_prezime' => (string) $r['naziv']
    ); 
}

上面的修复将使您的代码正常工作,但我建议使用使用SQL别名的方法,如 @YourCommonSense 的答案如下.

The above fix will make your code work, but I recommend using the approach using SQL aliases as shown in @YourCommonSense's answer below.

这篇关于php pdo foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆