Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
PHP json_encode creates number index as string instead of an object

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?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda