gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:45:09 25 4
gpt4 key购买 nike

大家好,我正在尝试检索我的列,该列具有带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com