php - 如何在 JSON 响应中表示 MySql 零填充

标签 php mysql json laravel zerofill

大家好,我正在尝试检索我的列,该列具有带有 json 响应的零填充规范,但 php 似乎忽略了其中的零,所以我尝试使用 str_pad 来做同样的事情作为零填充工作,但它也忽略它! 那么我该如何解决这个问题呢? 这是我的代码

public function getGeneralPost(){
    $post =Post::inRandomOrder()->orderBy('created_at', 'DESC')->get();
    foreach ($post as $item){
        $categories = Category::where('id' , $item->post_subtype)->select('category_title')->first();
        $categories_type = Category::where('id' , $item->post_type)->select('category_title')->first();
        $item->post_subtype = $categories->category_title;
        $item->post_type = $categories_type->category_title;
        $item->id = str_pad($item->id ,10,'0',STR_PAD_LEFT);// here I am usting str_pad     
    }
    $success['posts'] =$post;
    return response()->json(['code'=>'success','success' => $success], $this->successStatus);
}

最佳答案

正如评论中已经指出的,id 列似乎默认转换为 int,这将恢复通过 str_pad( )

要避免此问题,您可以将填充的 id 存储在没有适当转换的单独字段中,或者您可以获取对象的属性,而不是更改对象,更改它们并使用它们返回您的结果。

来自framework code itself ,也可以在返回对象之前覆盖它们的 $keyType 属性:

public function getGeneralPost() {
    $post = Post::inRandomOrder()->orderBy('created_at', 'DESC')->get();
    foreach ($post as $item) {
        $categories = Category::where('id' , $item->post_subtype)->select('category_title')->first();
        $categories_type = Category::where('id' , $item->post_type)->select('category_title')->first();
        $item->post_subtype = $categories->category_title;
        $item->post_type = $categories_type->category_title;

        $item->setKeyType('string');
        $item->id = str_pad($item->id ,10,'0',STR_PAD_LEFT);
    }
    $success['posts'] = $post;
    return response()->json(['code'=>'success','success' => $success], $this->successStatus);
}

关于php - 如何在 JSON 响应中表示 MySql 零填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831490/

相关文章:

json - JSON模式-递归模式定义

json - 如何使用 Powershell 遍历 JSON 属性

php - SQL 查询不会连接我的结果

mysql - SQL 触发器 - 更新日期早于当前日期的字段

php - 如何在godaddy Cpanel中为php文件运行cron作业?

mysql - 使用 INNER JOIN 时出现不明确的错误

java - 如何为 Jersey 1.0 客户端设置自定义 Jackson ObjectMapper

php - 如何使用关系在 yii SQL 语句上创建别名?

php - file_get_contents 未找到存在的文件

php - 无法在 Laravel 中的模型 View 中显示数据