I can’t add jsonArray return

Asked

Viewed 26 times

0

I have a following problem:

function send_notification(){
$jsonArray = json_decode($result);
$cont_sucesso +=  $jsonArray->success;
$cont_falha   +=  $jsonArray->failure;
}

for ($i = 0; $i < $num / 1000; $i++) {
 $Status = send_notification();
.....
}
console.log($cont_sucesso); 
echo("Total SUCESSO: ".$cont_sucesso);
echo("</br>");
echo("Total FALHAS: " .$cont_falha);
echo("</br>");
echo "Total de mensagens enviadas: ".$cont; 

I can’t add up the value of $jsonArray->success; I have a loop and inside that loop I call function that returns jsonArray But I need to add his comeback to display at the end of the loop, where I’m missing?

Edit: Json

{"multicast_id":5985558851077455261,"success":254,"failure":746,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"message_id":"0:1478517570268212%f17b55e1f9fd7ecd"}]}
  • Post the json you are using

  • my json is right, because if I put echo($jsonArray->Success); it shows me the amount

  • Zica is in these 2 variables $cont_success and $cont_failure. To almost playing in the session and rescuing later.

  • Is giving some PHP error or simply does not calculate?

  • it does not add up, no error

1 answer

1


Your problem are the scopes of variable.

function send_notification(){
$jsonArray = json_decode($result);
$cont_sucesso +=  $jsonArray->success; //esta é a variavel dentro do escopo da func send_notification()
$cont_falha   +=  $jsonArray->failure;
}

for ($i = 0; $i < $num / 1000; $i++) {
 $Status = send_notification();
.....
}
console.log($cont_sucesso); 
echo("Total SUCESSO: ".$cont_sucesso); //esta é OUTRA variavel no escopo local (fora da send_notification())
echo("</br>");
echo("Total FALHAS: " .$cont_falha);
echo("</br>");
echo "Total de mensagens enviadas: ".$cont; 

I did a little test on http://sandbox.onlinephpfunctions.com/ with the following code

$result = '{"multicast_id":5985558851077455261,"success":254,"failure":746,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"message_id":"0:1478517570268212%f17b55e1f9fd7ecd"}]}';

function send_notification($result){
    global $cont_sucesso, $cont_falha ; //Agora estou setando as vars do escopo da função como global

    $jsonArray = json_decode($result);
    $cont_sucesso +=  $jsonArray->success;
    $cont_falha   +=  $jsonArray->failure;
}


$cont_sucesso =0;
$cont_falha =0;

for ($i = 0; $i < 10; $i++) {
 $Status = send_notification($result);
}
echo("Total SUCESSO: ".$cont_sucesso);
echo("</br>");
echo("Total FALHAS: " .$cont_falha);
echo("</br>");
  • Perfect!!! Just declare them as global that worked. global $cont_success, $cont_fault ;

  • Thanks for the help Bartholomew

Browser other questions tagged

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