获取 JSON 编码响应中的数组键

get the array key in a json encoded response

本文关键字:数组 响应 JSON 编码 获取      更新时间:2023-09-26

我有这个 json 编码数组

请求解析器.php

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

和 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"]);
    }
});

我正在尝试做的是获取数组键并使用if语句对其进行过滤,例如(请参阅下文)

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

如何从请求解析器获取 JSON 编码响应中的数组键.php? 任何帮助,想法和线索将不胜感激。

使用 Object.keys 函数。这样:

var keys = Object.keys(jsonResponse);

这将返回一个键数组。然后由您来迭代数组并使用密钥执行任何操作。使用后续 JSON 对象对函数进行递归调用将允许您检索所有键。