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

时间:2018-04-14 23:07:04

标签: php arrays json

正如您在JSON文件中看到的那样,这看起来并非如此必要。 我从input-s获取值并将其添加到数组并通过AJAX.发送它一个简单的数组我知道如何转换,但多维数据不是。可以吃什么功能?我尝试用“键”创建一个数组,但是有很多麻烦,我从未到达终点,我确信它不对。告诉我你能做些什么。

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 个答案:

答案 0 :(得分:2)

我不能解决所有问题,如果我确定$input格式相同,我会做同样的事情:

<?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 :(得分:1)

如果您想要一个对象作为输出,则需要创建一个对象:

$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);

$user = new stdClass();

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

$phones = new stdClass();

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

$user->phones = $phones;

$users = new stdClass();
$users->user1 = $user;

echo json_encode($users);

输出:

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