Replace foreach php by each jquery

Asked

Viewed 279 times

0

I’m using jQuery to print returns from a JSON Web Service, the script works normally, but the page loading is very slow, I’m using PHP tags within my jQuery script, I would like to use only jQuery and I saw that the function each serves to go through Arrays, but I’m not sure how to apply it, and also I’m not sure if the way I wrote the code is correct, could give me tips on how to proceed?

php agenda.

<?php

$dt = date('Y') . '';
$dm = date('m') . '';

$api_campeonatos = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL&ano=2018&status=A';
$campeonatos = wp_remote_get( $api_campeonatos );
$campeonato = json_decode( wp_remote_retrieve_body( $campeonatos ), true );

$api_resultados = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL&inicio=2018-'. $dm .'-01&fim='. $dt .'-12-31';
$resultados = wp_remote_get( $api_resultados );
$resultado = json_decode( wp_remote_retrieve_body( $resultados), true);

$api_equipes = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL';
$equipes = wp_remote_get( $api_equipes );
$equipe = json_decode( wp_remote_retrieve_body( $equipes ), true );

$api_locais = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL';
$locais = wp_remote_get( $api_locais );
$local = json_decode( wp_remote_retrieve_body( $locais ), true );

$api_categorias = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL';
$categorias = wp_remote_get( $api_categorias );
$categoria = json_decode( wp_remote_retrieve_body( $categorias ), true );

$api_modalidades = 'https://sportsmanager.com.br/api/[email protected]&token=SXLSO8342HSDE78623GVS7234GNMSKL';
$modalidades = wp_remote_get( $api_modalidades );
$modalidade = json_decode( wp_remote_retrieve_body( $modalidades ), true );

$retorno_resultados = array();

if(!is_array($equipe) && !is_array($local) && !is_array($categoria) && !is_array($modalidade)){

    print_r('Não encontrado');

}else{

$col =  array_column($equipe, 'codigo');

$loc =  array_column($local, 'codigo');

$cat =  array_column($categoria, 'codigo');

$mod =  array_column($modalidade, 'codigo');

    foreach($campeonato as $camp){

            if(empty($camp) && !is_array($camp)){

            }else{

                foreach($resultado as $result){

                    if(empty($result) && !is_array($result)){

                }else{

                    if(isset($camp['categoria']) && isset($camp['modalidade']) && isset($result['mandante']) && isset($result['visitante']) && isset($result['local']) && isset($result['data'])) {

                        $categorizacao = '';
                        $key1 = array_search($camp['categoria'], $cat); 

                        if($key1){
                            $categorizacao = $categoria[$key1]['nome'];
                        }

                        $modalidadez = '';
                        $key2 = array_search($camp['modalidade'], $mod);

                        if($key2){
                            $modalidadez = $modalidade[$key2]['nome'];
                        }

                        $mandante = '';
                        $key3 = array_search($result['mandante'], $col);

                        if($key3){
                            $mandante = $equipe[$key3]['nome'];
                        }

                        $visitante = '';
                        $key4 = array_search($result['visitante'], $col);

                        if($key4){
                            $visitante = $equipe[$key4]['nome'];
                        }

                        $localizacao = '';
                        $key5 = array_search($result['local'], $loc);

                        if($key5){
                            $localizacao = $local[$key5]['nome'];
                        }

                        $data = $result['data'];
                        $data = date('d/m/Y', strtotime($data));

                        $i = 0;

                        if(isset($camp['codigo']) && isset($result['campeonato']) && $camp['codigo'] == $result['campeonato']){
                            $retorno_resultados[++$i][] = array(
                                'mandante' => $result['mandante'], 
                                'visitante' => $result['visitante'],
                                'nm_mandante' => $mandante,
                                'nm_visitante' => $visitante,
                                'nm_cat' => $categorizacao,
                                'nm_mod' => $modalidadez,
                                'nm_local' => $localizacao,
                                'id' => $camp['codigo'],
                                'modalidade' => $camp['modalidade'],
                                'categoria' => $camp['categoria'],
                                'data' => $result['data'],
                                'data_certa' => $data,
                                'placar1n' => $result['placar1n'],
                                'placar2n' => $result['placar2n'],
                                'placar1p' => $result['placar1p'],
                                'placar2p' => $result['placar2p'],
                                'placar1s' => $result['placar1s'],
                                'placar2s' => $result['placar2s'],
                                'jogo' => $result['jogo'],
                                'horario' => $result['horario'],
                                'jogo' => $result['codigo'],
                            );
                        };
                    };
                };
            };
        };
    };
};

?>

jQuery

<script>

 $(function() {

    <?php foreach($retorno_resultados as $val){ ?>

    var html3 = '';
    var id='';

    <?php foreach($val as $res){ ?>


    html3 += '<tr><td><?php echo $res['data_certa'];?>&nbsp às &nbsp<?php echo $res['horario'];?></td><td><?php echo $res['nm_local'];?></td><td><?php echo $res['nm_mandante'];?></td><td><?php echo $res['nm_visitante'];?></td><td><?php echo $res['nm_mod']?>&nbsp<?php echo $res['nm_cat']?></td></tr>';

    id = <?php echo $res['id'] ?>;

    <?php } ?>
    $('#equipesTbody').html(html3);

    <?php } ?>

});

</script>

HTML

    <div class="agenda-modalidades">

    <?php include_once 'agenda.php'; ?>

        <table id="agendatabelas" class="table table-bordered">
            <thead>
                <tr>
                    <th>Data</th>
                    <th>Local</th>
                    <th>Mandante</th>
                    <th>Visitante</th>
                    <th>Mod / Cat</th>
                </tr>
            </thead>

            <tbody id="equipesTbody">

            </tbody>
            <tfoot>
                <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                </tr>
            </tfoot>
        </table>
    </div>
  • You can only do this by using AJAX to play a PHP and recover the values in JS.

  • I use php to filter the data in another function, I would like to optimize jquery, it is difficult?

  • Why are you using jQuery if you already have the records in PHP? You don’t have access to the element #equipesTbody from PHP?

  • it’s my first time consuming Web Service, I haven’t found anything that helps me do it in php, so I went to jquery, I’m a beginner yet.

  • Can you show the HTML that generates the table that will show the teams? Where do you have the element #equipesTbody. You can edit that code and change that table, if yes, I would suggest that you use what you already have in PHP to show results there directly, instead of putting them on the page for jQuery to "catch" and then update the table?

  • I’ve added the information as you requested, I’m doing it as follows

Show 1 more comment

2 answers

1


PHP and include_once

In PHP when you include other files in a file (include, include_once), when processing that file, PHP, will manage that code as if it were a whole file (the one that calls the include), therefore, variables defined within a file that is in a include, are accessible in the father.

Showing information

With the information you posted, and without being able to test, what I would do is php agenda. remove the tag <script> where you have jQuery, everything inside it, erased up to the tag that closes PHP ?>, remove the tag even, but stop there, without closing PHP.

IS good practice when the file only has PHP

If a file is pure PHP code, it is preferable to omit the closing tag at the end of the file. Preventing the existence of blank spaces or lines after the tag, which can cause undesirable effects, because PHP will start the output buffer when there is no intention of the programmer to send some output at this point of the script.

Next, in HTML, in the table where you want to list the results, update the part of equipesTbody to be so

<tbody id="equipesTbody">
<?php foreach($retorno_resultados as $val): ?>
    <?php foreach($val as $res): ?>
        <tr>
            <td><?php echo $res['data_certa'];?>&nbsp; às &nbsp;<?php echo $res['horario'];?></td>
            <td><?php echo $res['nm_local'];?></td>
            <td><?php echo $res['nm_mandante'];?></td>
            <td><?php echo $res['nm_visitante'];?></td>
            <td><?php echo $res['nm_mod']?>&nbsp;<?php echo $res['nm_cat']?></td>
        </tr>
    <?php endforeach; ?>
<?php endforeach; ?>
</tbody>

Performance

In fact, your performance problem seems to be in the number of calls to external Apis you make. There are several ways to improve this aspect, but I think for now, getting it to work is the most important, improve performance can ask another question later.

  • it worked!! thank you very much. Please could you tell me too, concerning the performance so I can research it?

  • You have a few ways to do that. The simplest thing would be to see if you really need to call in all these Apis to show you the information you need. Another option is to directly use the library Requests (https://developer.wordpress.org/reference/classes/requests/) and the method request_multiple (https://developer.wordpress.org/reference/classes/requests/request_multiple/) to trigger all requests at the same time (async). It is already included in wordpress, hence suggest this. You have here (in English) a short explanation https://torquemag.io/2017/09/guide-async-http-requests-wordpress/

0

Try to use something like:

$(document).ready(function(){
    $.get( "http://meusite.com/", function(data) {
         var obj = JSON.parse(data);

        obj.forEach(function(o, index){
            console.log(o);
        });
    });
});

Try this and put the console result.log there

  • in the url location I place the json return url or site url?

  • If you search this JSON for a URL, put the URL instead of http://meusite.com/

  • IF you already have this JSON in javascript, delete the second and penultimate line and put your JSON instead of JSON.parse(date); the third line.

  • var obj = YOUR JSON HERE; obj.foreach(Function(o, index){ console.log(o); //will scroll through your json item by item and the values will be in the variable });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.