Christine Ong
Christine Ong

Reputation: 51

Setting array for json in Laravel

I'm trying to output the following with the

data: [{ rank: 2, state: 1, count: 3, }, { rank: 2, state: 3, count: 3, }, { rank: 1, state: 1, count: 2, }, { rank: 11, state: 4, count: 2, },],

but I'm getting extra [] & {} with the following code.

data: [[{rank: "2"},{state: "3"},{count: "3"},],[{rank: "2"},{state: "1"},{count: "3"},],[{rank: "1"},{state: "1"},{count: "2"},],[{rank: "11"},{state: "4"},{count: "2"},],],

Tried with many format to store the data without creating extra braces but not sure where is generating it. This is my code:

for ($i = 1; $i <= (sizeof($dataDB)/3); $i++){
        $d_temp = [];
        foreach ($dataDB as $k => $v) {
            $ks = explode("_", $k);
            $k1 = $ks[0];
            $k2 = $ks[1];
            if ($k1 == $i) {
                $d_temp[] = [ $k2 => $v ];
            }
        }
        $data[] = $d_temp;
    }

Except this method, what's the way to store the named array without extra {} in between?

Upvotes: 0

Views: 56

Answers (2)

Alex Alvarado
Alex Alvarado

Reputation: 131

Change $d_temp[] = [$k2 => $v]; for $d_temp[$k2] = $v;

Check the bracketing.

Upvotes: 1

Anton Proshkovsky
Anton Proshkovsky

Reputation: 21

This is because you add $d_temp as the first element in the $data array.

Solution:

$data = $d_temp;

Or do not use the array $data, but just get $d_temp

Upvotes: 0

Related Questions