dongli1887 2018-04-14 23:07
浏览 62
已采纳

如何将多维关联数组转换为JSON?

As you can see in the JSON file, this looks not so necessary. I get values from input-s and add it to the array and send it via AJAX. A simple array I know how to convert, but a multidimensional one is not. Can eat what that function? I tried to create an array with "keys", but there is a lot of trouble, I never reached the end , and I'm sure it's not right. Tell me what you can do.

i want this
{   
   "user1" : {
      first_name":"Michael",
      "last_name":"Podlevskykh",
       "phones" : {
           "phone_1":"5345",
            "phone_2":"345345",
            "phone_3":"123"
        }
    }
}

 //this is what i see
JSON
[
    {"first_name":"Michael"},
    {"last_name":"Podlevskykh"},
        [{"phone_1":"5345"},
            {"phone_2":"345345"},
            {"phone_3":"0991215078"}
        ]
]

PHP

//[["5345", "345345", "123"], "Michael", "Podlevskykh"]

$userInfo = (json_decode($_POST["phones"], true));

$namePhones = ["phone_1", "phone_2", "phone_3"];
$nameUser = ["first_name", "last_name"];
$jsonPhones = $userInfo;
$nameLName = $userInfo;

$jsonPhones = array_splice($jsonPhones, 0, 1);
$nameLName = array_splice($nameLName, -2);

foreach ($jsonPhones[0] as $key => $value) {
    $phones[] = array($namePhones[$key] => $jsonPhones[0][$key]);
}

foreach ($nameLName as $key => $value) {
    $usersName[] = array($nameUser[$key] => $nameLName[$key]);
}

array_push($usersName, $phones);

echo "<pre>";
echo json_encode($usersName);
//[ 
 // {"first_name":"Michael"},{"last_name":"Podlevskykh"},
//  [{"phone_1":"5345"},{"phone_2":"345345"},{"phone_3":"123"}]
//]
  • 写回答

2条回答 默认 最新

  • doudanglang5826 2018-04-14 23:16
    关注

    I don't get all the complications, I would do something like this if I'm sure the $input format is the same:

    <?php
    $input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';
    $input = json_decode($input, true);
    
    $output = [
        'user1' => [
            'first_name' => $input[1],
            'last_name' => $input[2],
            'phones' => [
                'phone_1' => $input[0][0],
                'phone_2' => $input[0][1],
                'phone_3' => $input[0][2]
            ]
        ]
    ];
    
    echo '<pre>';
    echo json_encode($output);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里