【问题标题】:Parse Json Encode Array PHP error解析 Json 编码数组 PHP 错误
【发布时间】:2014-08-21 14:14:37
【问题描述】:

这是我的问题:

我有一个 PHP 文件,它应该返回多条记录, 一切正常......但是,我不知道为什么,可能是因为某个地方的小错误......现在它不再工作了......

我的 Json_encode(my php) 返回这个:

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

而不是简单地:

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

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

我已经一次又一次地检查了我的 php 文件,但我没有找到这个“错误数组”的来源......

感谢帮助

这里是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;
}

【问题讨论】:

  • 请发布您的 php 代码...我们是程序员,不是魔术师 xD
  • 就是这样,魔术师 ;D
  • 你试过json_encode(array_values($array))吗?
  • 请发送var_dump($myArray);的输出

标签: php jquery arrays json parsing


【解决方案1】:

看起来您正在为 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"]

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

【讨论】:

  • 好吧...我刚刚意识到问题并不总是发生...!!
  • 不,它只会发生在某些情况下,如果您不输入这个,如果:if(!(is_numeric($benef['ADRESSE']))) 并且因此有非连续键
  • 我不明白...为什么这个 json 用这样的数字键对我的数据进行编码?我的数据在那里,这些不是空记录...
  • 确实如此。在您的示例中,{"1":{"id":"2222","name":"ERESRS"},"2":{"id":"1111","name":"LJLJM"}} 没有“0”记录,因此不返回该记录(因此为空)。如果$benef['ADRESSE'] 不是数字,则永远不会设置该数组元素并且该元素的键在$myArray 中为空。
  • O...M...F...*... !!!!!你太棒了...问题只是我必须删除的 else {$i++;}...之前没有考虑过...非常感谢您的帮助和耐心...;p
猜你喜欢
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多