I have an array which look like this :
Result 1:
{
"error_code": 0,
"error_message": "",
"return_data": {
"items": [
{
"id": 462,
"users": "1,36,38"
},
{
"id": 462,
"users": "1,4"
},...... //same for 20 result
]
}
}
I want the users
to convert to an array,and separate by the comma,so the whole result will look like this :
The result I want:
{
"error_code": 0,
"error_message": "",
"return_data": {
"items": [
{
"id": 462,
"users": [
{
"user_id": 1
},
{
"user_id": 36
},
{
"user_id": 38
}
],
}.. //other result
]
}
}
Here is what I try :
$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;
}
After I assign the array to $res with this line of code $res['return_data']['items']['users'] = $usersArray;
,my result become like below,I state the problem inside the code :
{
"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"
}
}
}
}
So my question is,how can I convert a String
in an array to an array,assign value to the key,and make it inside the array?
Somebody please help..Thanks