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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制