如何将数组中的字符串转换为数组并将它们组合在一起?

时间:2018-06-19 03:32:38

标签: php arrays

我有一个看起来像这样的数组:

结果1:

{
 "error_code": 0,
 "error_message": "",
 "return_data": {
    "items": [
        {
            "id": 462,
            "users": "1,36,38"
        },
        {
            "id": 462,
            "users": "1,4"
        },...... //same for 20 result
    ]
 }
}

我希望users转换为数组,并用逗号分隔,因此整个结果将如下所示:

我想要的结果:

{
    "error_code": 0,
    "error_message": "",
    "return_data": {
        "items": [
            {
                "id": 462,
                "users": [
                    {
                        "user_id": 1
                    },
                    {
                        "user_id": 36
                    },
                    {
                        "user_id": 38
                    }
                ],
            }.. //other result
        ]
    }
}

以下是我尝试的内容:

$res = "array the get the Result 1";
$items = //"I get the items array"

foreach ($items as $key => $item) {
    $usersArray = array(); //create a new Array

    //spilt the string to array separate with ","
    $usersIdArray = explode(',', $items['users']);

    //assign the "user_id" key to each value 
    foreach ($userIdArray as $key => $user) {

        $usersArray['user_id'] = $user;

    }
    //assign the result back to $res
    $res['return_data']['items']['users'] = $usersArray;
}

使用这行代码$res['return_data']['items']['users'] = $usersArray;将数组分配给$ res后,我的结果如下所示,我在代码中说明了问题:

{
"error_code": 0,
"error_message": "",
"return_data": {
    "items": {
        "0":{ <-- // here suddenly appear a number for each result 
            "id": 462,
            "users": "1,36,38" //here nothing change (I want the array appear here)
        },
        "1":{
            "id": 462,
            "users": "1,36,38"
        },
        "2":{
            "id": 462,
            "users": "1,36,38"
        },
        "users": { //the array appear here but not the position I want..and it only appears 1 time.
            "user_id": "38"
        }

    }
  }
}

所以我的问题是,如何将数组中的String转换为数组,为键赋值,并将其放入数组中?

有人请帮忙..谢谢

1 个答案:

答案 0 :(得分:1)

与上面的评论一样,您可以在第一时间完成此操作,因此您不需要进行其他结构转换,但无论如何,您的代码已经存在,只需要创建另一个嵌套,因为您需要另一个层面:

所以你需要另一个级别:

"users": [
    {
        "user_id": 1
    },
    {
        "user_id": 36
    },
    {
        "user_id": 38
    }
],

因此,在代码中,只需添加[]即可。这转化为:

foreach ($items as $key => $item) {
    $usersArray['id'] = $item['id'];
    $usersArray['users'] = array(); //create a new Array
    $usersIdArray = explode(',', $item['users']);
    foreach ($usersIdArray as $key => $user) {
        $usersArray['users'][] = array('user_id' => $user); // push each batch of key pair "user_id" key and value "each exploded id"
        // another level     ^
    }
    $res['return_data']['items'][] = $usersArray;
}

在这里fiddle检查一下。