将包含带引号的值的逗号分隔字符串转换为具有硬编码键的关联数组的数组
我需要将字符串从这样转换
"name1", "b", "2", "name2", "c", "3", "name3", "b", "2", ....
为这样的数组:
$arr[0]['name'] = "name1";
$arr[0]['char'] = "b";
$arr[0]['qnt'] = "2";
$arr[1]['name'] = "name2";
$arr[1]['char'] = "c";
$arr[1]['qnt'] = "3";
$arr[2]['name'] = "name3";
$arr[2]['char'] = "b";
$arr[2]['qnt'] = "2";
我尝试使用 explode()
将字符串转换为数组,但它无法按需要工作。
I need to convert a string from this:
"name1", "b", "2", "name2", "c", "3", "name3", "b", "2", ....
to an array like this:
$arr[0]['name'] = "name1";
$arr[0]['char'] = "b";
$arr[0]['qnt'] = "2";
$arr[1]['name'] = "name2";
$arr[1]['char'] = "c";
$arr[1]['qnt'] = "3";
$arr[2]['name'] = "name3";
$arr[2]['char'] = "b";
$arr[2]['qnt'] = "2";
I tried to use explode()
to convert the string to an array but it does not work as needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
输出:
Output:
如果你不关心数组键是数字,你可以这样做:
If you do not care about the array keys being numeric, you can do:
解析包含带引号的值的 csv 字符串,然后将该平面数组拆分为 3 元素块,然后使用硬编码键伪造关联行。
代码:(演示)
Parse the csv string containing quoted values, then split that flat array into 3-element chunks, then forge associative rows using hardcoded keys.
Code: (Demo)