简体   繁体   中英

Iterate loop in php associative array using Jquery

I have PHP associative array and I use JQuery AJAX to get the result array but my problem is when that result is pass to jquery and use looping to extract each Sequence,Percent and Date then that extracted data will store to new Jquery Array for data manipulation purposes. Please see my sample code so far.

sample code PHP ARRAY:

$Sequence=array(
    array("Seq1","20%"),
    array("Seq2","40%"),
    array("Seq3","60%"),
    array("Seq4","80%"),
    array("Seq5","100%")
);

****For loop here****

$ResultArray[$arrayIndex]=array(
    'Sequence' => $Sequence[$arrayIndex][0],
    'Percent' => $Sequence[$arrayIndex][1],
    'Date' => $row['exactDate']
);


echo json_encode($ResultArray); // then pass result array to jquery

JQUERY :

$(document).ready(function(){

    var ListOfSequence = []
    var ListOfPercentage = [];
    var ListOfDates = [];

    $("#button").click(function(){

        var _WOID = $('#txtWOID').val();

        $.ajax({
            url:'getStatus.php',
            type:'POST',
            data:{id:_WOID},
            dataType:'json',
            success:function(output){
                //here is where the problem begin
                for (var key in output) {
                    if (output.hasOwnProperty(key)) {
                        //here where extracted data will store to designated array
                        ListOfSequence.push(key);//<---store extracted Sequence
                        ListOfPercentage.push(key);//<---store percentage
                        ListOfDates.push(output[key]);//<---store dates                
                    }
                }

                ListOfPercentage.reverse();

                console.log(ListOfPercentage);
                console.log(ListOfDates);
                console.log(ListofSequence);

            }

        });

    });

});

and here's the console.log:

在此处输入图片说明

Thank you in advance

在将内容发送到浏览器之前,您应该设置json响应标头,如下所示:

header('Content-type: application/json'); die(json_encode($ResultArray);)

Since you are already using jQuery you could use $.each() :

$(document).ready(function(){

  var ListOfSequence = []
  var ListOfPercentage = [];
  var ListOfDates = [];

  $("#button").click(function(){

    var _WOID = $('#txtWOID').val();

    $.ajax({
      url:'getStatus.php',
      type:'POST',
      data:{id:_WOID},
      dataType:'json',
      success:function(json){
         $.each(json, function(index, object){
             ListOfSequence.push(object.Sequence);
             ListOfPercentage.push(object.Percent);
             ListOfDates.push(object.Date);
         });

      }

    });

  });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM