简体   繁体   中英

Separate Id and name in key of JSON

I have data on worker in my database in JSON format. 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. I want id from key so that I can use it and I want to use it in Laravel Controller(PHP). Thanks,

You can use split here

 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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