如何将结果行添加到json对象

时间:2014-04-10 14:55:33

标签: php jquery ajax json

我使用ajax更新我的数据。 Ajax调用我的function.php,我用一个开关来阻止运行哪个函数。我将结果保存在json对象中($ resp = new stdClass)。 但是如何将多行(具有多列)保存到json对象中?

function func1($mysqli){
    $result = $mysqli->query("select * from order");

    ///how do i fetch all rows in a loop and save it correctly to my json object?

    return json;
}

$resp = new stdClass;

if (isset($_POST["action"])) {
    switch($_POST["action"])) {
    case "func1":
        $resp->data = func1($mysqli);
        break;
    }
}
echo json_encode($resp);

1 个答案:

答案 0 :(得分:3)

这是在数组中存储行并返回它的函数。如果查询失败,则返回null

function func1($mysqli){
    $result = $mysqli->query("select * from `order`");

   if ($result){
     $data = array();

     while($row = $result->fetch_assoc()){
       $data[] = $row ;
     }

     return $data ;

   } else {
     return null ;
   }
}

在你的代码中,你已经在STDClass中保存了一个返回值,所以没关系:

case "func1":
    $resp->data = func1($mysqli);
    break;
}