求助:mysqli_fetch_array查询结果输出格式不符合预期的问题
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:
UsePDO::FETCH_ASSOCto get only associative keys, orPDO::FETCH_COLUMNto 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:
Usemysqli_fetch_assoc()in your loop, ormysqli_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

