作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
大家好,我正在尝试检索我的列,该列具有带有 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/
我是一名优秀的程序员,十分优秀!