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

如何从对象数组获取内部数组?服务端取tax数组及CI代码实现

Hey David, let's tackle your questions one by one—this is a super common task when working with nested data, so I'll cover both frontend data extraction and the CodeIgniter backend setup you need.

1. Extracting Inner Arrays from an Object Array (Frontend)

First, let's clarify two common scenarios depending on your data structure:

Scenario A: Single invoice object with a nested tax array

If your $scope.invoice looks like this (a single object containing a tax array):

$scope.invoice = {
  customer_name: "John Doe",
  total_amount: 1500,
  tax: [
    { rate: 5, amount: 75 },
    { rate: 10, amount: 150 }
  ]
};

You can directly grab the tax array with:

const taxArray = $scope.invoice.tax;

Scenario B: Array of invoice objects (each with a tax array)

If you're dealing with a list of invoices like this:

const invoices = [
  { id: 1, customer: "Jane", tax: [{ rate: 5, amount: 50 }] },
  { id: 2, customer: "Bob", tax: [{ rate: 8, amount: 80 }] }
];
  • To get all individual tax arrays (as a nested array):
    const allTaxArrays = invoices.map(inv => inv.tax);
    // Result: [[{rate:5, amount:50}], [{rate:8, amount:80}]]
    
  • To flatten into a single array of all tax items:
    const allTaxItems = invoices.flatMap(inv => inv.tax);
    // Result: [{rate:5, amount:50}, {rate:8, amount:80}]
    

2. Server-Side: Extract tax Array & CodeIgniter Setup

Since your frontend uses $http.post to send $scope.invoice to /ci/index.php/invoiceCtrl/addInvoice, here's how to handle this in CodeIgniter:

Step 1: Database Table Structure (Example)

First, make sure you have two tables to store invoice and tax data:

  • invoices table: id (PK), customer_name, total_amount, created_at
  • taxes table: id (PK), invoice_id (FK to invoices.id), rate, amount

Step 2: Model (application/models/Invoice_model.php)

Create a model to handle database operations:

class Invoice_model extends CI_Model {
    // Insert main invoice record and return its ID
    public function add_invoice($invoice_data) {
        $this->db->insert('invoices', $invoice_data);
        return $this->db->insert_id();
    }

    // Insert multiple tax records linked to an invoice
    public function add_taxes($invoice_id, $taxes) {
        foreach ($taxes as $tax) {
            $tax_record = [
                'invoice_id' => $invoice_id,
                'rate' => $tax['rate'],
                'amount' => $tax['amount']
            ];
            $this->db->insert('taxes', $tax_record);
        }
        return true;
    }
}

Step 3: Controller (application/controllers/invoiceCtrl.php)

The controller will receive the POST data, extract the tax array, and use the model to save everything:

class invoiceCtrl extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('Invoice_model');
        // Load helpers/libraries if needed
        $this->load->helper('url');
    }

    public function addInvoice() {
        // Angular's $http.post sends JSON by default, so we need to read raw input
        $post_payload = json_decode($this->input->raw_input_stream, true);

        // Extract main invoice data (exclude the tax array)
        $invoice_data = [
            'customer_name' => $post_payload['customer_name'],
            'total_amount' => $post_payload['total_amount'],
            'created_at' => date('Y-m-d H:i:s')
        ];

        // Insert invoice and get its ID
        $invoice_id = $this->Invoice_model->add_invoice($invoice_data);

        // Extract and insert tax records if they exist
        if (!empty($post_payload['tax'])) {
            $this->Invoice_model->add_taxes($invoice_id, $post_payload['tax']);
        }

        // Send success response back to frontend
        echo json_encode([
            'status' => 'success',
            'invoice_id' => $invoice_id,
            'message' => 'Invoice and taxes saved successfully'
        ]);
    }
}

Note on Frontend Request

Your existing Angular code should work fine, but just to confirm, the $scope.invoice must include the tax array as part of the object you're sending. The controller expects that structure to extract the tax data correctly.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:19:43