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

97
Visualizações
Using a PHP array inside a JS For loop

I explored a bunch of related questions but to no avail. I use json_encode to pass on a PHP variable to JS and it works fine. <?php echo json_encode($datasets[0]);?>);

But when I try to do the same thing inside a JS for loop using the index of the loop it only picks up null. How can I use the the index of the PHP array $datasets[] inside a JS for loop?

const DT = [];
    for (let i = 0; i < 10; i++) {
    DT.push(<?php echo json_encode($datasets[i]);?>);
    };
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

PHP executes before any of the JavaScript executes, so it cannot evaluate $datasets[i], because that i is not known in PHP. Moreover, it would only evaluate it once, because there is no PHP loop.

The way to do this, is to let PHP pass the whole data set to JavaScript:

const DT = <?php echo json_encode(array_slice($datasets, 0, 10));?>;

If the PHP array is also 10 items long, then you can omit the array_slice part. But if your intention was to just get the first 10 items of a longer PHP array, you'll need it.

about 4 years ago · Juan Pablo Isaza Relatório

0

you are missing some quotes and you can't iterate over a php object in javascript

it should be

const DT = JSON.parse('<?php echo json_encode($datasets);?>')
    

or if you want to do a for loop for some reason you could do this

const DT = [];
<?php for($i = 0; $i < 10; $i++): ?>
DT.push(JSON.parse('<?php echo json_encode($datasets[$i]);?>'))
<?php endfor; ?>

about 4 years ago · Juan Pablo Isaza 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