S
S
s0prano2018-11-27 09:27:18
PHP
s0prano, 2018-11-27 09:27:18

How to make correct json output?

Through foreach, I iterate and insert data into the array:

foreach ($banners as $key => $id) {
$banner = Banner::where('id', $id)->first();
                $this->data[$key] = array(
                    'id' => $banner->id,
                    'url' => $banner->url,
                    'name' => $banner->name,
                    'image' => $banner->image
                );
}

with json_encode($this->data) I get:
spoiler
5bfce39e994eb274470287.png

why json strings in [...]?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
netrox, 2018-11-27
@s0prano

Tryjson_encode($this->data, JSON_FORCE_OBJECT);

A
alexalexes, 2018-11-27
@alexalexes

You are this:

array(
                    'id' => $banner->id,
                    'url' => $banner->url,
                    'name' => $banner->name,
                    'image' => $banner->image
                );

You put in $this->data by the key $key, it follows that $this->data is an array, so it is decoded in brackets [].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question