如何在PHP Json API输出中返回int和string?
我是PHP Json新手。我可以知道如何在一个PHP JSON API输出中返回int和string值吗?我想返回类别名称,类别图像为字符串,类别ID为int。请帮助。多谢各位 示例代码如下:- Category.php如何在PHP Json API输出中返回int和string?,php,json,api,Php,Json,Api,我是PHP Json新手。我可以知道如何在一个PHP JSON API输出中返回int和string值吗?我想返回类别名称,类别图像为字符串,类别ID为int。请帮助。多谢各位 示例代码如下:- Category.php <?php header("Content-Type: application/json"); defined('BASEPATH') OR exit('No direct script access allowed'); class Category extends C
<?php
header("Content-Type: application/json");
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends CI_Controller {
// ~/category/main
public function main() {
$this->load->model("Category_model");
$result = $this->Category_model->getCategoryMain();
if (count($result) == 0) {
echo json_encode('Error');
} else {
echo json_encode($result, JSON_UNESCAPED_SLASHES);
}
}
}
<?php
class Category_model extends CI_Model {
function __construct() {
$this->load->database();
}
// ~/category/main
public function getCategoryMain() {
$sql = "select c.name, c.image, c.category_id from category c left join product p on p.category_id = c.category_id";
$result = $this->db->query($sql);
$records = $result->result_array();
return $records;
}
}
使用(int)
或其intval()
值键入类别id
:
public function getCategoryMain() {
$sql = "select c.name, c.image, c.category_id from category c left join product p on p.category_id = c.category_id";
$result = $this->db->query($sql);
$records = array();
foreach( $result->result_array() as $r ) {
$r['category_id'] = intval( $r['category_id'] );
$records[] = $r;
}
return $records;
}
这种类型约定的原因是您的db驱动程序。如果您使用Postgres数据库,您将获得准确的数据格式
顺便说一句,你可以这样做,很容易
public function getCategoryMain() {
$sql = "select c.name, c.image, c.category_id from category c left join product p on p.category_id = c.category_id";
$result = $this->db->query($sql);
//$row = $result->fetch_assoc(); //edited
foreach ($query->result_array() as $row)
{
$row['category_id']=(int) $row['category_id'];
}
}
Use(int)或intval()都可以工作,但对于性能强制转换(int)更好
有一个比较我在尝试应用此代码时遇到了此错误消息:-消息:调用未定义的方法CI_DB_mysqli_result::fetch_assoc()
fetch_assoc()不是代码签名或查询生成器的方法它是mysqli的actaullay方法,但您使用的是“代码签名或查询生成器”。我错了,没有弄清楚。嗨@dilusha,谢谢你的更新,但是Wolf发布的内容对我有用。所以我记下了他的答案。对不起,谢谢你的帮助!没关系。快乐的codingHi@the wolf,你的解决方案是有效的!但是,我可以知道如何在您的示例中使用(int)以获得更好的性能吗?另外,如果有多个字段需要更改为int,我如何才能实现这一点?