-1

I have an array inside a foreach to generate data in json, but I should add a comma to validate the code. But I can not ... how can I do it?

$obj = array(
    'name' => 'value', 
    'img' => 'value', 
    'url' => 'value',
);

echo json_encode($obj);

I have this code

{"name":"value","img":"value","url":"value"}
{"name":"value","img":"value","url":"value"}
{"name":"value","img":"value","url":"value"}

but I would like this code

[
    {"name":"value","img":"value","url":"value"},
    {"name":"value","img":"value","url":"value"},
    {"name":"value","img":"value","url":"value"}
]
Patrick Q
  • 6,373
  • 2
  • 25
  • 34
gracekweb
  • 1
  • 2
  • 1
    Use `$obj[] = array(...);` to make object into an array of those. – IncredibleHat Oct 09 '18 at 20:54
  • I already tried but it happens a strange thing ... they are added these] incorrectly .... I tried this code .... but the last comma does not make me validate the code $obj = array( 'name' => 'value', 'img' => 'value', 'url' => 'value', ); $json = json_encode($obj); echo $json; echo ','; – gracekweb Oct 09 '18 at 21:03
  • 1
    _"they are added these] incorrectly"_ - I doubt that json_encode added anything incorrectly. It's more likely that you made some mistake when built the array. Show us that attempt and we can help you sort it out. – M. Eriksson Oct 09 '18 at 21:08
  • https://stackoverflow.com/q/14251490/2943403 , https://stackoverflow.com/q/6739871/2943403 – mickmackusa Oct 09 '18 at 21:17
  • https://stackoverflow.com/q/17097136/2943403 , https://stackoverflow.com/q/44379007/2943403 – mickmackusa Oct 09 '18 at 21:28

1 Answers1

2

Don't echo the JSON in the loop. Put all the objects in another array, and convert that to JSON.

Start with an empty array:

$array = [];

In the loop push onto that array:

$array[] = array(
    'name' => 'value', 
    'img' => 'value', 
    'url' => 'value',
);

After the loop is done, do:

echo json_encode($array);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 4
    @gracekweb Instead of editing the title as solved, mark the answer that helped you solve it as solution. – Johan Oct 09 '18 at 21:16