-1

I have this array:

{"0": {"item1": "somevalue", "item2": "somevalue"}},
{"1": {"item3": "somevalue", "item4": "somevalue"}},
{"3": {"item5": "somevalue", "item6": "somevalue"}}

Using PHP, I want to convert it to this format with square brackets at the start and end and no numerical keys:

[{"item1": "somevalue", "item2": "somevalue"}},
{{"item3": "somevalue", "item4": "somevalue"}},
{{"item5": "somevalue", "item6": "somevalue"}}]
Graham
  • 7,431
  • 18
  • 59
  • 84
Umar Tanveer
  • 77
  • 2
  • 8
  • We are always glad to help and support new coders but ***you need to help yourself first. :-)*** After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Feb 06 '18 at 21:31
  • @Umar can you explain more details? do you want to remove 0,1,3 keys and make regular numeric keys ? – Krish Feb 06 '18 at 21:36
  • https://stackoverflow.com/questions/43693595/how-to-remove-the-unwanted-nested-keys-from-json – Progrock Feb 06 '18 at 22:02

1 Answers1

0

Your first array is probably the result of a PHP array without continuous keys. Maybe you/someone deleted key 2. You can decode the JSON, re-index the array, and encode it again.

In code:

$array2 = json_encode(array_values(json_decode($array1, TRUE))); 

Explanation:

Curly braces denote JSON objects, and PHP arrays will be encoded as JSON objects, if they have string keys or non continuous keys. Square keys denote JSON arrays.

Normally json_decode will return a stdClass object for JSON objects. Since we don't want that we pass TRUE as a second parameter, and get an associative array. array_values 'removes' the keys from from the result (returns an array whose keys start from 0 and move up).json_encode encodes the result with the square parentheses you want.

jh1711
  • 2,288
  • 1
  • 12
  • 20