0

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;
}
4
  • Please post your php code...we are coders, not magicians xD Commented Aug 21, 2014 at 14:15
  • this is it, magician ;D Commented Aug 21, 2014 at 14:19
  • Have you tried json_encode(array_values($array))? Commented Aug 21, 2014 at 14:22
  • Please pos the output of var_dump($myArray); Commented Aug 21, 2014 at 14:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

well... i just realized that the problem does not ALWAYS happen...!!
No, it will only happen when, in some case, you do not enter this if: if(!(is_numeric($benef['ADRESSE']))) and thus there's non-consecutive keys
i don't get it... why does this json encodes my data with numeric keys like this? my data is there, these are not empty records...
Indeed it is. In your example, {"1":{"id":"2222","name":"ERESRS"},"2":{"id":"1111","name":"LJLJM"}} has no record for "0", so that record is not returned (thus, empty). If the $benef['ADRESSE'] is not numeric, then that array element is never set and the key for that element is empty in $myArray.
O...M...F...*... !!!!! you're awesome... the problem was only that else {$i++;} that i had to remove... didn't think about that before... thanks a lot for your help and patience... ;p
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.