解析Json编码数组PHP错误

时间:2014-08-21 14:14:37

标签: php jquery arrays json parsing

这是我的问题:

我有一个PHP文件,应该返回多条记录, 一切都很好......但是,我不知道为什么,可能是因为某个地方有点小错误......现在它已不再适用......

我的Json_encode(我的php)返回:

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

而不仅仅是:

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

以前有人遇到过这个问题吗?

我已经一次又一次检查了我的php文件,而且我找不到这个" false array"来自......

感谢您的帮助

这是js代码:

$.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();
                    }
                });

这是一个名为:

的php文件
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;
}

1 个答案:

答案 0 :(得分:2)

看起来您正在为PHP数组手动设置keys或以某种方式对其进行编辑。比较以下结果:

<?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"}

正如@amphetamachine建议的那样,一个可能的解决方案就是:

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

另一项有趣的测试(你的案例):

<?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"]

如果你想设置不连续的数组键,我们可以从中得到你需要的<{em> array_values()