我是PHP Json的新手。我可以知道如何在一个PHP JSON API输出中返回int和字符串值吗?我想以字符串返回类别名称,类别图像,但以int返回类别ID。请帮忙。谢谢。
示例代码如下:-
Category.php
<?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);
}
}
}
Category_model.php
<?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;
}
}
答案 0 :(得分:1)
使用category_id
或其(int)
值对intval()
进行类型转换:
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;
}
答案 1 :(得分:1)
这种类型约定的原因是您的数据库驱动程序。如果您使用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'];
}
}
答案 2 :(得分:1)
使用(int)或intval()都可以工作,但是对于性能转换(int)更好。
有一个比较here