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

如何在PHP中按指定格式展示多维关联数组数据

如何将多维关联数组整理为整洁格式展示?

方法一:手动提取固定结构数据(适合你的作业场景)

因为你的数组结构固定,直接通过键名逐层访问数据,再用HTML标签排版成整洁格式,新手容易上手:

<?php
// 假设你的API返回数组是$weatherData
$weatherData = [
    'wind' => ['speed' => 5, 'direction' => 'North West', 'directionDegrees' => 310, 'unit' => 'KT'],
    'visibility' => ['mainVisibility' => '10SM'],
    'clouds' => [['height' => 25000, 'quantity' => 'few']],
    'remark' => 'automated station with a precipitation discriminator sea level pressure of 1021.7 HPa hourly temperature of 17.2°C and dew point of -1.1°C',
    'day' => 6,
    'time' => '22:52:00',
    'airport' => [
        'name' => 'Hartsfield Jackson Atlanta International Airport',
        'city' => 'Atlanta',
        'country' => ['name' => 'United States'],
        'iata' => 'ATL', 'icao' => 'KATL',
        'latitude' => 33.6367, 'longitude' => -84.428101,
        'altitude' => 1026, 'timezone' => -5, 'dst' => 'A'
    ],
    'temperature' => 17, 'dewPoint' => -1, 'altimeter' => 1021
];

// 格式化输出
echo "<h3>📌 机场信息</h3>";
echo "<ul>";
echo "<li>名称: {$weatherData['airport']['name']}</li>";
echo "<li>城市: {$weatherData['airport']['city']}</li>";
echo "<li>国家: {$weatherData['airport']['country']['name']}</li>";
echo "<li>IATA代码: {$weatherData['airport']['iata']}</li>";
echo "<li>ICAO代码: {$weatherData['airport']['icao']}</li>";
echo "</ul>";

echo "<h3>🌤️ 天气数据</h3>";
echo "<ul>";
echo "<li>观测时间: {$weatherData['day']}日 {$weatherData['time']}</li>";
echo "<li>气温: {$weatherData['temperature']}°C</li>";
echo "<li>露点温度: {$weatherData['dewPoint']}°C</li>";
echo "<li>能见度: {$weatherData['visibility']['mainVisibility']}</li>";
echo "<li>风速风向: {$weatherData['wind']['direction']} ({$weatherData['wind']['directionDegrees']}°),{$weatherData['wind']['speed']} {$weatherData['wind']['unit']}</li>";
echo "<li>云况: {$weatherData['clouds'][0]['quantity']} 云高 {$weatherData['clouds'][0]['height']} 英尺</li>";
echo "<li>修正海平面气压: {$weatherData['altimeter']} hPa</li>";
echo "</ul>";

echo "<h3>ℹ️ 备注信息</h3>";
echo "<p>{$weatherData['remark']}</p>";
?>

方法二:递归遍历通用方法(适配任意多维数组)

如果以后数组结构可能变化,用递归函数自动遍历所有非空数据,无需手动修改键名:

<?php
function printFormattedArray($array, $indent = 0) {
    $spacing = str_repeat('&nbsp;', $indent * 4);
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            echo "{$spacing}<strong>{$key}:</strong><br>";
            printFormattedArray($value, $indent + 1);
        } else {
            if (!empty($value)) { // 跳过空值
                echo "{$spacing}<strong>{$key}:</strong> {$value}<br>";
            }
        }
    }
}

// 调用函数输出
printFormattedArray($weatherData);
?>

说明

  • 手动提取法:完全可控输出格式,适合固定结构的作业场景,直接复制代码替换你的数组即可。
  • 递归遍历法:自动处理所有层级的数组,适合结构不固定的情况,输出会自动缩进区分层级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:30:55