我有一个表单,其中包含一些由 JSON 填充的选择元素。它看起来像下面这样。
{
"suppliers":
{"1":"Amazon","2":"Apple"},
"manufacturers":
{"1":"Apple","2":"Lenovo"},
"categories":
{"2":"Tablet","3":"Laptop","4":"Desktop"},
"status":
{"1":"Ready to Deploy","2":"Deployed","3":"Damaged","4":"Destroyed"}
}
如何按值(名称)而不是键(id)排序?我已经尝试了所有我能想到的方法,并且搜索了我能想到的每一个短语,但它仍然没有按照我需要的字母顺序排序。请注意,如果直接在浏览器中查看 JSON,下面的 orderBy 将以正确的顺序对其进行排序,但在表单中,我的选择元素仍然按键排序。
public function getFormData()
{
$suppliers = DB::table('supplier')->orderBy('sup_name','asc')->pluck('sup_name','id');
$manufacturers = DB::table('manufacturer')->orderBy('man_name','asc')->pluck('man_name','id');
$categories = DB::table('category')->where('parent_id', 1)->orderBy('cat_name','asc')->pluck('cat_name', 'id');
$status = DB::table('status')->orderBy('status','asc')->pluck('status', 'id');
return json_encode(compact('suppliers', 'manufacturers', 'categories', 'status'));
}
编辑:
使用来自@Snapey 的以下语法,我能够获得正确的排序顺序
public function getFormData()
{
$suppliers = DB::table('supplier')->orderBy('sup_name','asc')->get(['sup_name','id']);
$manufacturers = DB::table('manufacturer')->orderBy('man_name','asc')->get(['man_name','id']);
$categories = DB::table('category')->where('parent_id', 1)->orderBy('cat_name','asc')->get(['cat_name', 'id']);
$status = DB::table('status')->orderBy('status','asc')->get(['status', 'id']);
return json_encode(compact('suppliers', 'manufacturers', 'categories', 'status'));
}
新输出:
{
"suppliers":
[{"sup_name":"Amazon","id":1},{"sup_name":"Apple","id":2}],
"manufacturers":
[{"man_name":"Apple","id":1},{"man_name":"Lenovo","id":2}],
"categories":
[{"cat_name":"Desktop","id":4},{"cat_name":"Laptop","id":3},{"cat_name":"Tablet","id":2}],
"status":
[{"status":"Damaged","id":3},{"status":"Deployed","id":2},{"status":"Destroyed","id":4},{"status":"Ready to Deploy","id":1}]
}
不幸的是,现在我在我的选择元素中得到了“object Object”并且值被关闭了。
忽然笑
米脂