简体   繁体   English

在json编码的响应中获取数组键

[英]get the array key in a json encoded response

I have this json encoded array 我有这个JSON编码的数组

requestparser.php requestparser.php

 $array = array("ph" => array("phweb" => "yes", "phemail" => "yesss"));
 echo json_encode($array);

and ajax post type request for sending and processing the return response. ajax post类型请求,用于发送和处理返回响应。

$.ajax({
    type: 'POST',
    url: 'requestparser.php',
    data: { "request" : "pull" },
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    cache: false,
    success: function(result) {
    alert(result["ph"]["phweb"]);
    alert(result["ph"]["phemail"]);
    }
});

what I'm trying to do is to get the array key and filter it with if statement, like (refer below) 我想要做的是获取数组键并使用if语句对其进行过滤,例如(请参阅下文)

var thearraykey = array key
if (thearraykey === "ph"){
    alert(array key)
}

how to get the array key that was in the json encoded response from requestparser.php? 如何从requestparser.php获取json编码响应中的数组键? any help, ideas and clues would be greatly appreciated. 任何帮助,想法和线索将不胜感激。

Use the Object.keys function. 使用Object.keys函数。 Like so: 像这样:

var keys = Object.keys(jsonResponse);

That returns an array of keys. 那会返回一个键数组。 Then it's up to you to iterate over the array and do what you will with the keys. 然后,您可以遍历数组并使用键进行操作。 Recursive calls to the function with subsequent JSON objects will allow you to retrieve all the keys. 对带有后续JSON对象的函数的递归调用将允许您检索所有键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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