php嵌套数组递归搜索返回数组key
<span style="color: #0000ff;">var</span> rewardTypes={"experience":{"\u7ecf\u9a8c\u503c":{"1":"\u660e\u661f\u6587\u827a\u996d","2":"\u6587\u827a","3":"\u963f\u91cc\u5df4\u5df4\u7f51"}},"money":{"\u865a\u62df\u8d27\u5e01":{"little_red_heart":"\u5c0f\u7ea2\u5fc3","golden_heart":"\u91d1\u8272\u4e4b\u5fc3","diamond_heart":"\u94bb\u77f3\u5fc3"}}};
使用1:
getShowText("3",rewardTypes,true);
返回:
"经验值"
使用2:
getShowText("3",rewardTypes);
返回:
"阿里巴巴网"
<span style="color: #008000;">//</span><span style="color: #008000;">递归搜索key对应文本,isParent=true则返回所在父节点对应文本名,false则返回匹配到的节点文本</span><span style="color: #000000;">function getShowText(keyid,data,isParent){ </span><span style="color: #0000ff;">var</span> title=<span style="color: #800000;">""</span><span style="color: #000000;">; </span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> key <span style="color: #0000ff;">in</span><span style="color: #000000;"> data){ </span><span style="color: #0000ff;">if</span>(keyid==<span style="color: #000000;">key){ </span><span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">typeof</span>(data[key])==<span style="color: #800000;">"</span><span style="color: #800000;">object</span><span style="color: #800000;">"</span><span style="color: #000000;">){ </span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> item <span style="color: #0000ff;">in</span><span style="color: #000000;"> data[key]){ title</span>=<span style="color: #000000;">item; </span><span style="color: #0000ff;">break</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">break</span><span style="color: #000000;">; }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{ title</span>=<span style="color: #000000;">data[key]; } </span><span style="color: #0000ff;">break</span><span style="color: #000000;">; }</span><span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">typeof</span>(data[key])==<span style="color: #800000;">"</span><span style="color: #800000;">object</span><span style="color: #800000;">"</span><span style="color: #000000;">){ title</span>=<span style="color: #000000;">getShowText(keyid,data[key],isParent); </span><span style="color: #0000ff;">if</span>(title!=<span style="color: #800000;">""</span><span style="color: #000000;">){ </span><span style="color: #0000ff;">if</span><span style="color: #000000;">(isParent){ </span><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">var</span> item <span style="color: #0000ff;">in</span><span style="color: #000000;"> data[key]){ title</span>=<span style="color: #000000;">item; } } </span><span style="color: #0000ff;">break</span><span style="color: #000000;">; } } } </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> title;}</span>