This might be an easy one but I'm struggling to get it done.
I have this following array in php which I want to json_encode as an array of objects. What's the best way of doing this in php?
Array
(
[6946] => Array
(
[AssetGroupName] => Computer
[AssetGroupID] => 14
)
[6945] => Array
(
[AssetGroupName] => Laptop
[AssetGroupID] => 15
)
)
Json output I'm trying to get.
{
"data": [
{
"AssetGroupName": "Computer",
"AssetGroupID": "12"
},
{
"AssetGroupName": "Laptop",
"AssetGroupID": "15"
}
]
}
2 Answers 2
That's relatively simple, first, you need to create the proper array in PHP with nested data subarray then just to get rid of keys (or in the other order it's up to you). When using numeric keys that are not starting from 0 and increased by 1 they are just considered as keys in an associative array.
$array = [
'data' => [
6946 => [
'AssetGroupName' => 'Computer',
'AssetGroupID' => 14
],
6945 => [
'AssetGroupName' => 'Laptop',
'AssetGroupID' => 15
]
]
];
$array['data'] = array_values($array['data']);
echo json_encode($array);
answered Apr 8, 2021 at 0:57
biesior
55.8k10 gold badges130 silver badges186 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Florian
Thanks for the explanation. Using
array_values did the trick. Thanks again.> $array = [
> ['AssetGroupName' => 'computer', 'AssetGroupID' => 14], ];
>
> echo json_encode(['data' => $array]);
1 Comment
biesior
I can bet, that OP didn't want to rewrite arrays data manually to get rid of the keys.
lang-php
json_encode()will encode an associative array as a JSON object.