Ajax JSON多数组 - 确定数组索引包含特定值

时间:2013-09-05 03:11:58

标签: json jquery

我通过JQuery Ajax从PHP返回一个JSON多数组,并且想要确定哪个数组包含一个值以便访问该数组中的值(同样对于其他数组 - 最多返回三个数组。

$.ajax({
type: "POST",
url: "scripts/get_model_imaging_report.php",
data: {
        case_id:caseId,
        level:currentLevel
},
dataType: "json",
success: function(returnedData) {

}
});

PHP;

$case = $_POST['case_id'];
$level = $_POST['level'];


$query = "SELECT * FROM model_image_report WHERE case_fk = '$case' AND level = '$level'";
$result = mysql_query($query, $connection) or die(mysql_error());

$data = array();
while ($row = mysql_fetch_array($result)) {
        $data[] = array(
        'image_report_type' => $row['image_report_type'],
        'subject' => $row['subject'],
        'clinical' =>  $row['clinical'],
        'study_type' =>  $row['study_type'],
        'report' =>  $row['report'],
        'comment' =>  $row['comment'],
        'image' =>  $row['image'],
        'image_annotated' =>  $row['image_annotated']
        );
} 
echo json_encode($data);

我需要检查的关键是'image_report_type',值可以是'核','放射学'和'超声波'。

然后我需要访问那些'image_report_type'=='nuclear'的数组中的值。

JSON数组如下所示:

[{"image_report_type":"nuclear","subject":"Brain Scan","clinical":"Clinical","study_type":"nuclear image scan.","report":"Report","comment":"Comment","image":"original_image_case_3_level_1_nuclear.jpg","image_annotated":"annotated_image_case_3_level_1_nuclear.png"},{"image_report_type":"ultrasound","subject":"Brain Scan","clinical":"Clinical","study_type":"Ultrasound image scan.","report":"Report","comment":"Comment","image":"original_image_case_3_level_1_nuclear.jpg","image_annotated":"annotated_image_case_3_level_1_nuclear.png"}]

2 个答案:

答案 0 :(得分:3)

您可以使用jQuery each函数完成此操作。

function(returnedData) {
  $.each(returnedData, function(i,o) {
      if (o.image_report_type == "nuclear") {
         //Do Something
      }
  });
}

这是展示此技术的jsFiddle

答案 1 :(得分:0)

试试这个http://jsfiddle.net/mN4LF/3/

的Javascript

function findIndexOf(data, searchField, searchValue){
    var result = new Array();
    for(var i = 0; i < data.length; i++){
        if(data[i][searchField] == searchValue){
            result.push(i);
        }
    }

    return result;
}