请求提供在复杂PHP数组中递归查找指定值的代码实现
递归查找嵌套JSON中指定键的存在性
嘿,我懂你现在的困扰了——那些只能处理二级结构的查找方案确实顶不住这种多层嵌套的JSON对吧?下面给你写个通用的递归函数,不管嵌套多深都能精准判断目标键是否存在,还能扩展成获取对应的值。
示例递归函数(JavaScript)
这个函数会逐层遍历对象的所有属性,一旦找到目标键就返回true,遍历完所有层级都没找到就返回false:
function doesKeyExist(obj, targetKey) { // 先判断当前值是不是有效对象,不是的话直接返回false if (typeof obj !== 'object' || obj === null) { return false; } // 检查当前对象有没有目标键 if (obj.hasOwnProperty(targetKey)) { return true; } // 递归遍历当前对象的每一个属性 for (const key in obj) { if (doesKeyExist(obj[key], targetKey)) { return true; } } // 所有层级都搜完没找到,返回false return false; }
结合你的JSON数据使用
假设你的JSON已经解析成了JavaScript对象data,要判断state是否存在,直接调用就行:
// 你的JSON解析后的对象 const data = { "company": { "id": "123456", "name": "Test Company LLC.", "FEIN": "22-2222222", "address": { "address_line_1": { "street": "1 Street St, Suite 12", "city": "San Francisco", "postalCode": "123456" }, "address_line_2": { "state": "CA", "country": "USA" } }, "phone": "1-800-XXX-XXXX", "fax": "1-800-XXX-XXXX", "email": "admin@abc.com", "URL": "www.abc.com" }, "producer": { "id": "LLXXXX", "name": "Test Name", "phone": "555-555-5555", "mobile": "555-555-5555", "fax": "555-555-5555", "email": "test@abc.com", "producerSubCode": "111", "NIPRId": "123456", "stateProducerId": "12344" } }; // 查找state键是否存在 const stateExists = doesKeyExist(data, 'state'); console.log(stateExists); // 输出: true
扩展:如果需要获取键对应的值
要是你不仅想判断存在性,还想拿到state的具体值,可以稍微修改函数:
function findKeyVal(obj, targetKey) { if (typeof obj !== 'object' || obj === null) { return undefined; } if (obj.hasOwnProperty(targetKey)) { return obj[targetKey]; } for (const key in obj) { const result = findKeyVal(obj[key], targetKey); if (result !== undefined) { return result; } } return undefined; } // 使用示例 const stateValue = findKeyVal(data, 'state'); console.log(stateValue); // 输出: "CA"
这个思路换其他语言(比如Python、Java)也适用,核心就是递归遍历嵌套结构,直到找到目标键为止。
内容的提问来源于stack exchange,提问作者iamharshit
相关产品推荐
相关产品推荐

