3

I have the following example code in PHP:

$data = array(
 'hello',
 'world',
 'hi'
);

$ret = array();
$ret['test'] = array();
$ret['testing'] = array();

foreach($data as $index => $value){
  if($index < 1){
      $ret['test'][$index]['val'] = $value;
      $ret['test'][$index]['me'] = 'index < 1';
  }
  else {
      $ret['testing'][$index]['val'] = $value;
      $ret['testing'][$index]['me'] = 'index >= 1';
  }
}

echo json_encode($ret);

I would expect this to be the JSON output:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":[
    {
       "val": "world",
       "me": "index >= 1"   
    },
    {
       "val": "hi",
       "me": "index >= 1"
    }
  ]
}]

However, what ends up happening is that I end up with the following:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":{
    "1":{
       "val": "world",
       "me": "index >= 1"   
    },
    "2":{
       "val": "hi",
       "me": "index >= 1"
    }
  }
}]

The "1" and "2" keys appear despite being an int and despite the correct rendering of test when the same counter variable is used. Is there a way I can make sure that testing becomes an array of JSON objects?

1 Answer 1

4

Because the array doesn't start with index 0 but with index 1, it's encoded as an JSON object instead of an JSON array.

You can use the array_values() function to remove the indexes and only keep the values.

Example:

$ret['testing'] = array_values($ret['testing'])
echo json_encode($ret);

But because you don't need the index at this moment, you can also refactor your code to this:

foreach($data as $index => $value){
  if($index < 1){
    $ret['test'][] = array(
      'val' => $value,
      'me' => 'index < 1'
    );
  }
  else {
    $ret['testing'][] = array(
      'val' => $value,
      'me' => 'index >= 1'
    );
  }
}
echo json_encode($ret);

This way, the arrays will always start with index 0.

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

Comments

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.