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

如何从PHP/MySQL提取逗号分隔值并转为按钮展示

Hey there! Let's break down what's going on with your size display issue and fix it step by step.

问题分析

You've successfully stored multi-select sizes in your database using implode(', ', $array) (resulting in formats like 2, 3, 4), but hit a snag when trying to display them as button/link elements—only a single size was showing up instead of all selected ones.

Looking at your original extraction code:

while($row_t4 = mysqli_fetch_array($run_get_sizes)){
 $pr_sizes = $row_t4['size_title'];
 foreach($pr_sizes as $key=>$value){
 // ... output $value
 }
}

The core issue here is that $row_t4['size_title'] is a single string (e.g., "2") for each row returned by your query—not an array. The foreach loop doesn't work as expected here, and you end up only rendering the last size fetched.

Working Solution (And Why It Works)

The final code you landed on is the right approach—let's break down how it fixes the problem:

  1. Collect all size links first
    Create an empty array to store each formatted size link. Loop through your query results, wrap each size in the desired HTML, and push it into the array:

    $availableSizeArr = [];
    while($row_t4 = mysqli_fetch_array($run_get_sizes)){
     $pr_sizes = $row_t4['size_title'];
     $availableSizeArr[] = "<a href='shop-sidebar.php' rel='tag'>$pr_sizes</a>";
    }
    
  2. Combine links into a display-ready string
    Use implode(', ', $availableSizeArr) to join all the links with a comma and space, so you can output them all at once:

    $availableSizes = implode(', ', $availableSizeArr);
    
  3. Render in your modal
    Replace the single $value in your modal HTML with $availableSizes:

    <span class='posted_in font-size-12'>Available Sizes - $availableSizes</span>
    
Quick Optimizations
  • Simplify your insertion code: You don't need to implode on every loop iteration—do it once after collecting all values:
    $tshirt_sizes_array = [];
    foreach($_POST['t_size'] as $value){
     $tshirt_sizes_array[] = $value;
    }
    $tshirt_sizes = implode(', ', $tshirt_sizes_array);
    
  • Watch for SQL injection: Your use of IN($t_sizes) works for your current setup, but if $t_sizes ever comes directly from untrusted user input, switch to prepared statements to avoid security risks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:47:58