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

PHP中传递数组并转换为含JSON数组字段的JSON的方法

Hey there! I get that working with PHP arrays to JSON can be tricky when you need nested array fields like invoice_lines and charges. Let's walk through exactly how to pull this off correctly.

Step 1: Build Your PHP Array with Nested Arrays

First, you'll define your main data array, making sure invoice_lines and charges are set as nested PHP arrays (this is key—json_encode will automatically convert these to JSON arrays later). You can populate them with whatever data you need, or leave them empty if you're adding data dynamically.

<?php
// Initialize your invoice data array
$invoiceData = [
    "description" => "Monthly SaaS Subscription",
    "annotations" => "Includes premium support add-on",
    "date" => "2024-05-20",
    "serie" => "INV-2024",
    "issued" => false,
    "number" => 47,
    "customer" => 108, // Replace with your actual customer ID
    "footer" => "Configuración del usuario.",
    "irm" => "Configuración del usuario - Términos y condiciones aplicables.",
    // Nested array for invoice lines
    "invoice_lines" => [
        [
            "product" => "Basic SaaS Plan",
            "quantity" => 1,
            "unit_price" => 99.99,
            "total" => 99.99
        ],
        [
            "product" => "Premium Support",
            "quantity" => 1,
            "unit_price" => 29.99,
            "total" => 29.99
        ]
    ],
    // Nested array for additional charges
    "charges" => [
        [
            "type" => "VAT",
            "rate" => 10,
            "amount" => 12.99,
            "description" => "Value Added Tax"
        ]
    ]
];
?>
Step 2: Convert the PHP Array to JSON

Next, use PHP's json_encode() function to turn your array into a valid JSON string. I recommend adding a couple of flags to make the output clean and handle special characters properly:

  • JSON_PRETTY_PRINT: Formats the JSON with indentation for readability (great for debugging)
  • JSON_UNESCAPED_UNICODE: Ensures accented characters (like those in your footer/irm fields) stay unescaped and readable
// Convert array to JSON
$jsonResult = json_encode($invoiceData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// Check for encoding errors (always a good practice!)
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Oops, JSON encoding failed: " . json_last_error_msg();
} else {
    // You can echo the JSON, save it to a file, or send it via API
    echo $jsonResult;
}
What the Final JSON Looks Like

Here's what the output will look like (matching your required structure with the nested arrays):

{
    "description": "Monthly SaaS Subscription",
    "annotations": "Includes premium support add-on",
    "date": "2024-05-20",
    "serie": "INV-2024",
    "issued": false,
    "number": 47,
    "customer": 108,
    "footer": "Configuración del usuario.",
    "irm": "Configuración del usuario - Términos y condiciones aplicables.",
    "invoice_lines": [
        {
            "product": "Basic SaaS Plan",
            "quantity": 1,
            "unit_price": 99.99,
            "total": 99.99
        },
        {
            "product": "Premium Support",
            "quantity": 1,
            "unit_price": 29.99,
            "total": 29.99
        }
    ],
    "charges": [
        {
            "type": "VAT",
            "rate": 10,
            "amount": 12.99,
            "description": "Value Added Tax"
        }
    ]
}

Quick tips:

  • If you need to add data to invoice_lines or charges dynamically, just use array_push() or direct assignment like $invoiceData['invoice_lines'][] = $newLineItem;
  • Make sure numeric fields like number and customer are integers (not strings) if that's what your target system expects—PHP will preserve the type when encoding.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:29:45