Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some confusion about why the following code does not work:

$data_set = array();
for($i=1; $i<=3; $i++)
{
  $data_val = array($i, $i*2);
  $data_set[] = $data_val;
}

echo json_encode($data_set);

What I expect is something like

[ [1,2], [2,4], [3,6] ]

What I get is an empty string.

But, If I do this

$data_set = array();
for($i=1; $i<=3; $i++)
{
  $data_val = array($i, $i*2);
  $data_set[] = json_encode($data_val);
}

echo json_encode($data_set);

I get something like this:

[ "[1,2]", "[2,4]", "[3,6]" ]

So, it seems like deeper Arrays do not work. What am I missing?

share|improve this question
5  
I tried running your first example and it gave me the expected result. i.e. [[1,2],[2,4],[3,6]] –  Drumbeg Jun 11 at 19:59
2  
Can you do var_dump($data_set); instead? Your code works: 3v4l.org/AiL2U –  Halcyon Jun 11 at 20:00
    
Works perfectly for me. –  VikingBlooded Jun 11 at 20:05

1 Answer 1

There is no reason to convert the elements of the array, then convert the entire

$data_set = array();
for($i=1; $i<=3; $i++)
{
  $data_set[] = array($i, $i*2);
}

echo json_encode($data_set);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.