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

Unity中如何拆分从数据库获取的文章数据字符串?

How to Split Your Article Database Data in Unity

Hey there! Let's figure out how to properly split that article data string you're fetching from your PHP script. First, the approach depends on what format your PHP is returning the data in—CSV (comma-separated values) or JSON are the most common (and easiest to work with) options, so I'll cover both below.

Before diving into splitting, let's create a simple class to store each article's data. This keeps your code clean and avoids messy loose variables:

[System.Serializable]
public class Article
{
    public string name;
    public int id;
    public string option1;
    public string option2;
    public string option3;
    public string valueChange;
}

Case 1: PHP Returns CSV Data

If your PHP script outputs each article as a new line, with columns separated by commas (like this):

"Fireball Guide,101,Buy Scroll,Learn from Wizard,Find in Dungeon,+15 Fire Damage\nHealing Basics,102,Use Potion,Visit Cleric,Rest at Inn,+20 Health"

Here's how to split and parse it in your DevideData method:

void DevideData(string data)
{
    // Split the full data string into individual article rows (ignore empty lines)
    string[] articleRows = data.Split(new char[] {'\n'}, System.StringSplitOptions.RemoveEmptyEntries);
    
    List<Article> allArticles = new List<Article>();
    
    foreach (string row in articleRows)
    {
        // Split each row into its 6 columns
        string[] columns = row.Split(',');
        
        // Make sure we have all 6 columns before processing (avoids errors)
        if (columns.Length == 6)
        {
            Article newArticle = new Article();
            // Trim whitespace from each column to clean up any extra spaces
            newArticle.name = columns[0].Trim();
            newArticle.id = int.Parse(columns[1].Trim());
            newArticle.option1 = columns[2].Trim();
            newArticle.option2 = columns[3].Trim();
            newArticle.option3 = columns[4].Trim();
            newArticle.valueChange = columns[5].Trim();
            
            allArticles.Add(newArticle);
            // Do whatever you need with the article here—add to UI, store in a game manager, etc.
            Debug.Log($"Loaded Article: {newArticle.name} (ID: {newArticle.id})");
        }
        else
        {
            Debug.LogWarning($"Skipping invalid row: {row} — Expected 6 columns, got {columns.Length}");
        }
    }
}

Note for CSV:

If your article names/options might contain commas (e.g., "Fireball, Explosive Version"), plain CSV will break. In that case, have your PHP output quoted CSV (e.g., "Fireball, Explosive Version",101,...), and use a more robust parser like TextFieldParser from Microsoft.VisualBasic.FileIO (you'll need to add using Microsoft.VisualBasic.FileIO; to your script).

Case 2: PHP Returns JSON Data (More Robust)

JSON is better for handling special characters and avoids parsing headaches. If your PHP script outputs a JSON array like this:

[{"name":"Fireball Guide","id":101,"option1":"Buy Scroll","option2":"Learn from Wizard","option3":"Find in Dungeon","valueChange":"+15 Fire Damage"},{"name":"Healing Basics","id":102,"option1":"Use Potion","option2":"Visit Cleric","option3":"Rest at Inn","valueChange":"+20 Health"}]

Here's how to parse it using Unity's built-in JsonUtility:

// First, add a wrapper class for the JSON array (JsonUtility needs a top-level object)
[System.Serializable]
public class ArticleList
{
    public List<Article> articles;
}

void DevideData(string data)
{
    try
    {
        // Convert the JSON string into our ArticleList object
        ArticleList articleList = JsonUtility.FromJson<ArticleList>(data);
        
        foreach (Article article in articleList.articles)
        {
            // Process each article
            Debug.Log($"Loaded Article: {article.name} (ID: {article.id})");
        }
    }
    catch (System.Exception e)
    {
        Debug.LogError($"Failed to parse JSON: {e.Message}");
    }
}

Pro Tip for JSON:

If you need more advanced JSON parsing (like handling nested objects or flexible types), you can use the Newtonsoft.Json package (available via Unity Package Manager by searching for "Newtonsoft Json").

Quick Checks

  • Double-check that your PHP script is outputting the data in a consistent format (no extra newlines or missing columns).
  • Test with a small sample of data first to catch parsing errors early.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:37:12