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

求助:mysqli_fetch_array查询结果输出格式不符合预期的问题

Fixing Your SQL Query Output Formatting Issue

Hey there! Let's break down how to turn that messy mixed array output into something more useful. The output you're seeing is a common result when database extensions (like PDO or mysqli) return both indexed and associative keys for query results—since your SQL uses AS Average, you're getting both the numeric index and the named key for each average value.

Here are a few straightforward solutions depending on what you need:

1. Get Clean Results Directly from the Query

Instead of letting the database driver return mixed arrays, configure it to only return the format you want:

  • If using PDO:
    Use PDO::FETCH_ASSOC to get only associative keys, or PDO::FETCH_COLUMN to pull just the average values as a flat array:
    // Fetch associative arrays (only the 'Average' key)
    $stmt = $pdo->query("SELECT AVG(your_column) AS Average FROM your_table GROUP BY your_grouping_column");
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Or fetch just the average values as a flat one-dimensional array
    $averages = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
    
  • If using mysqli:
    Use mysqli_fetch_assoc() in your loop, or mysqli_fetch_column() to get single values:
    $result = mysqli_query($conn, "SELECT AVG(your_column) AS Average FROM your_table GROUP BY your_grouping_column");
    $averages = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $averages[] = $row['Average'];
    }
    

2. Clean Up the Existing Array

If you already have that mixed array and need to reformat it, use array_column() to extract just the 'Average' values into a clean array:

// Your original array
$originalArray = Array ( [0] => Array ( [0] => 68686.4792 [Average] => 68686.4792 ) [1] => Array ( [0] => 83703.3284 [Average] => 83703.3284 ) [2] => Array ( [0] => 95899.7763 [Average] => 95899.7763 ) [3] => Array ( [0] => 115881.2429 [Average] => 115881.2429 ) [4] => Array ( [0] => 99444.4138 [Average] => 99444.4138 ) );

// Extract all 'Average' values
$cleanAverages = array_column($originalArray, 'Average');
// Result: Array ( [0] => 68686.4792 [1] => 83703.3284 [2] => 95899.7763 ... )

3. Format for Readable Output

If you need to present this data (e.g., to users), convert it to a more friendly format:

  • JSON (great for APIs or frontend):
    echo json_encode($cleanAverages, JSON_PRETTY_PRINT);
    
  • Simple text list:
    foreach ($cleanAverages as $avg) {
        echo "Average: $avg\n";
    }
    

Pick the approach that fits your end goal—whether you need a clean array for further processing, or a formatted output for display.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:14:09