You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多维数组遍历如何获取各子数组最后索引的指定元素值

实现方案

你可以通过以下PHP代码完成需求,PHP7.3及以上版本可直接使用:

// 用于存储所有提取到的日期
$extractedDates = [];
// 替换为你实际的数组变量名
$sourceArray = $yourOriginalArray;

$targetLevel = $sourceArray['Something']['Something1'][0];
foreach ($targetLevel as $nodeKey => $nodeValue) {
    // 过滤前缀为Something1.的节点,跳过@attributes等其他节点
    if (!str_starts_with($nodeKey, 'Something1.')) {
        continue;
    }
    // 取当前节点下的索引数组(无需硬编码下级节点名)
    $indexedList = current($nodeValue);
    // 取索引数组最后一位元素
    $lastItem = $indexedList[array_key_last($indexedList)];
    // 存入目标日期值
    if (isset($lastItem['DateLASTRETURNED'])) {
        $extractedDates[$nodeKey] = $lastItem['DateLASTRETURNED'];
    }
}

// 后续可直接使用$extractedDates中的日期,例如
// echo $extractedDates['Something1.1']; // 输出对应节点的日期值

如果你使用的是PHP7.3以下版本,替换取最后一个元素的逻辑即可:

// 兼容低版本PHP的写法
end($indexedList);
$lastItem = current($indexedList);

补充说明

  • 上述代码默认将日期以Something1.x作为键名存储,你可以根据自己的使用场景调整存储结构
  • 如果下级节点存在多个符合要求的索引数组,可再加一层遍历匹配即可

内容的提问来源于stack exchange,提问作者user15123815

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:15:01