Julo0sS
Julo0sS

Reputation: 2102

Parse Json Encode Array PHP error

Here is my problem :

I have a PHP file, that should return multiple records, everything worked fine... but, i don't know why, probably because of a little mistake somewhere... now it doesn't work anymore...

my Json_encode(my php) returns this :

{"1":{"id":"2222","name":"ERESRS"},"2":{"id":"1111","name":"LJLJM"}}

instead of simply :

[{"id":"2222","name":"ERESRS"},{"id":"1111","name":"LJLJM"}]

anybody had this issue before?

i already checked again and again my php file, and i don't find where this "false array" comes from...

thanks for help

Here is the js code :

$.ajax({
                    type : 'POST',
                    url : './php/getBenefListe.php',
                    data : {'id':idSoc},
                    error : function(){
                        alert('ERREUR MISE A JOUR DE LA LISTE');
                    },
                    success : function(response){
                        $("#benefListe").empty();
                        $('#benefListe').append($('<option>',{
                            value : '',
                            text : 'Choisissez dans la liste'
                        }));
                        alert("REPONSE : "+response);
                        var myData = JSON.parse(response);
                        for(var i=0;i<myData.length;i++){
                            var id = myData[i].id;
                            if(id-latestBenef > 0){
                                latestBenef = id;
                            }
                            var nom = myData[i].nom;
                            var prenom = myData[i].prenom;
                            var rue = myData[i].rue;
                            var numero = myData[i].num;
                            var boite = myData[i].bte;
                            var cp = myData[i].cp;
                            var loc = myData[i].loc;
                            if(rue!="" && numero!=""){
                                rue = rue+", "+numero;
                            }
                            if(cp!="" && loc!=""){
                                loc = "- "+cp+" "+loc;
                            }
                            var field = nom+" "+prenom+" ; "+rue+" "+boite+" "+loc;
                            $('#benefListe').append($('<option>',{
                                value : id,
                                text : field
                            }));
                        }
                        alert("B\351n\351ficiaire Ajout\351!");
                        $("#benefListe option[value="+latestBenef+"]").prop('selected',true);
                        $("#benefListe").change();
                    }
                });

here is the php file called :

include "./functions.php";
if(isset($_POST['id']) && ($_POST['id']!='')){
    $id = $_POST['id'];
    $db = connectToDb('test');
    $myArray = array();
    $i = 0;
    $getBenefIds = "SELECT DISTINCT IDPERSONNE FROM socrsp WHERE (IDSOCIETE = $id);";
    $benefIds = $db->prepare($getBenefIds);
    $benefIds->execute();
    $count = $benefIds->rowCount();
    if($count>0){
        foreach($benefIds as $benefId){
            $getBenef = "SELECT IDPERSONNE,NOM,PRENOM,ADRESSE,NUMERO,BTE,IDCOPOSTAL,CODEPAYS FROM personne WHERE IDPERSONNE = ".$benefId['IDPERSONNE'];
            $myBenef = $db->prepare($getBenef);
            $myBenef->execute();
            foreach($myBenef as $benef){
                if(!(is_numeric($benef['ADRESSE']))){
                    $myArray[$i]['id'] = $benef['IDPERSONNE'];
                    $myArray[$i]['nom'] = $benef['NOM'];
                    $myArray[$i]['prenom'] = $benef['PRENOM'];
                    $myArray[$i]['rue'] = '';
                    $myArray[$i]['num'] = '';

                    $myArray[$i]['rue'] = $benef['ADRESSE'];
                    $myArray[$i]['num'] = $benef['NUMERO'];
                    $myArray[$i]['bte'] = $benef['BTE'];

                    //RECUP CP ET LOCALITE
                    if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0') && ($benef['IDCOPOSTAL']!='2913'))&&($benef['CODEPAYS']=="B")){
                        $whereQuery = "SELECT CODEPOSTAL,LIBLOCALITE FROM copostal WHERE IDCOPOSTAL = ".$benef['IDCOPOSTAL'];
                        $where = $db->prepare($whereQuery);
                        $where->execute();
                        foreach($where as $w){
                            $myArray[$i]['cp'] = $w['CODEPOSTAL'];
                            $myArray[$i]['loc'] = $w['LIBLOCALITE'];
                        }
                    }else if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0'))&&($benef['CODEPAYS']!="B")){
                        $whereQuery = "SELECT CPEXTERNE,LOCEXTERNE FROM cpostext WHERE IDCPOSTEXT = ".$benef['IDCOPOSTAL'];
                        $where = $db->prepare($whereQuery);
                        $where->execute();
                        foreach($where as $w){
                            $myArray[$i]['cp'] = $w['CPEXTERNE'];
                            $myArray[$i]['loc'] = $w['LOCEXTERNE'];
                        }
                    }else{
                        $myArray[$i]['cp'] = '';
                        $myArray[$i]['loc'] = '';
                    }
                    $i++;
                }else{
                    $i++;
                }
            }
        }
    }
    echo json_encode($myArray);
    $db = null;
}

Upvotes: 0

Views: 285

Answers (1)

Francisco Presencia
Francisco Presencia

Reputation: 8860

It looks like you're setting manually the keys for the PHP array or editing it in some way. Compare the following results:

<?php

$a = ['hello', 'world'];
echo json_encode($a);
// ["hello","world"]

$b = [1 => 'hello', 2 => 'world'];
echo json_encode($b);
// {"1":"hello","2":"world"}

$b = ['hello', 'world', 'how', 'are', 'you'];
unset($b[2]);
echo json_encode($b);
// {"0":"hello","1":"world","3":"are","4":"you"}

As @amphetamachine suggest, a possible solution is this:

$b = [1 => 'hello', 2 => 'world'];
$b = array_values($b);
echo json_encode($b);
// ["hello","world"]

Another interesting test (your case):

<?php

$a = $b = [];
for ($i = 0; $i < 3; $i++) {
  $a[$i] = "test";
  if ($i != 1) {
    $b[$i] = "test";
    }
  }

echo json_encode($a);
// ["test","test","test"]

echo json_encode($b);
// {"0":"test","2":"test"}

echo json_encode(array_values($b));
// ["test","test"]

From which, we can get that you do need that array_values() if you want to set not-consecutive array keys.

Upvotes: 2

Related Questions