0

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"
      }
   ]
}
1
  • json_encode() will encode an associative array as a JSON object. Commented Apr 8, 2021 at 0:51

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. Using array_values did the trick. Thanks again.
0
> $array = [
>     ['AssetGroupName' => 'computer', 'AssetGroupID' => 14], ];
> 
> echo json_encode(['data' => $array]);

1 Comment

I can bet, that OP didn't want to rewrite arrays data manually to get rid of the keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.