1

How do I encode an array like this:

$myArray = "["user1","user2","user3"]"

into this dynamically:

{
"myArray": "user1, user2, user3"
}

I understand that the JSON above isn't an array but I still want it in that form. Also, JSON encode doesn't encode it exactly like how I want it.

zam
  • 58
  • 2
  • 9

1 Answers1

0

So to use the array and get a "non-array" in JSON as you show, you need to impode() and get the myArray as a key:

$myArray = ["user1","user2","user3"];

$myArray = implode(', ', $myArray);
echo json_encode(compact('myArray'), JSON_PRETTY_PRINT);

Alternately:

echo json_encode(['myArray' => implode(', ', $myArray)], JSON_PRETTY_PRINT);

Both yield:

{
    "myArray": "user1, user2, user3"
}

This is just really a one element array with a comma separated list as the data.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87