0

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?

3
  • change this $d_temp[] = [ $k2 => $v ]; to $d_temp = [ $k2 => $v ]; Commented Nov 8, 2020 at 19:04
  • @MustafaPoya Wouldn't that override $d_temp on every iteration? Commented Nov 8, 2020 at 19:15
  • Yes, it's overriding the d_temp on every iteration Commented Nov 9, 2020 at 5:39

2 Answers 2

1

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

Check the bracketing.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

No, it's not working. With this i'm getting the first set of foreach only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.