简体   繁体   English

在 JSON 的键中分隔 Id 和 name

[英]Separate Id and name in key of JSON

I have data on worker in my database in JSON format.我的数据库中有 JSON 格式的工人数据。 which looks like this看起来像这样

{"45051-Cortador 1 Siloc": "hsgvs", "45063-Nihil impedit quia": "okbbd",}

in this JSON Key contains id and name of user for example in first key 45051 is id and Cortador 1 Siloc is name of user.在此 JSON 密钥中包含 id 和用户名,例如第一个密钥45051是 id, Cortador 1 Siloc是用户名。 I want id from key so that I can use it and I want to use it in Laravel Controller(PHP).我想要来自密钥的 id 以便我可以使用它并且我想在 Laravel Controller(PHP) 中使用它。 Thanks,谢谢,

You can use split here你可以在这里使用 split

 const obj = { "45051-Cortador 1 Siloc": "hsgvs", "45063-Nihil impedit quia": "okbbd", }; const result = Object.keys(obj).map((s) => s.split("-")); console.log(result); result.forEach(([k, v]) => console.log(k, v));
 /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }

You can use collection您可以使用集合

 $result= collect(json_decode($json))->map(function ($item,$key){

        $data=explode("-",$key);

        return ['id'=>$data[0]??null,'name'=>$data[1]??null];
    })->values()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM