将JSON字符串转换为JSON数组 [英] Converting a JSON string to a JSON array

查看:163
本文介绍了将JSON字符串转换为JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的CSV文件

first_name,last_name,phone
Joseph,Dean,2025550194
Elbert,Valdez,2025550148

使用GitHub上的 csv-to-json.php 我会得到这样的输出

Using this csv-to-json.php from GitHub I get output like this

[{
    "first_name": "Joseph",
    "last_name": "Dean",
    "phone": "2025550194",
    "id": 0
}, {
    "first_name": "Elbert",
    "last_name": "Valdez",
    "phone": "2025550148",
    "id": 1
}]

这几乎是我想要的-但是不是

This is almost what I want - however instead of

"phone": "2025550194"

我需要

"phone": [{
    "type": "phone",
    "number": "2025550194"
}]

我该如何纠正?

推荐答案

如果您获得JSON字符串,那么您当然会首先使用以下命令将其转换为数组:

If you get the JSON string, then you would of course first convert it to an array with:

$arr = json_decode($json, true);

但是可能您已经有了该数组.然后,将其应用到该循环:

But probably you already have the array. You then apply this loop to it:

foreach($arr as &$row) {
    if (isset($row['phone'])) { // only when there is a phone number:
        $row['phone'] = [[ "type" => "phone", "number" => $row['phone'] ]];
    }
}

看到它在 eval.in 上运行.

这篇关于将JSON字符串转换为JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆