當前位置: 首頁> 最新文章列表> 快速提取電商訂單中的商品ID

快速提取電商訂單中的商品ID

M66 2025-06-07

在電商開發中,處理訂單信息時我們經常需要從訂單數組中提取特定的數據,比如商品ID。 PHP提供了一個非常實用的函數array_column() ,它可以輕鬆地從多維數組中提取某一列數據。本文將通過實例演示如何使用array_column()函數來快速提取電商訂單中的商品ID。

1. array_column()函數簡介

array_column()函數是PHP 內建的一個數組操作函數,它用於從多維數組中提取出某一列的數據。該函數的基本語法如下:

 array_column(array $input, mixed $column_key, mixed $index_key = null): array
  • $input : 需要操作的輸入數組。

  • $column_key : 提取的列名(可以是數組的鍵名)。

  • $index_key : 可選,結果數組的索引。

這個函數返回一個包含所提取列的數組。

2. 示例:提取電商訂單中的商品ID

假設我們有一組電商訂單數據,每個訂單包含多個商品,我們的目標是提取出這些商品的ID。

示例訂單數據:

 $orders = [
    [
        'order_id' => 'A123',
        'items' => [
            ['product_id' => 1001, 'quantity' => 2],
            ['product_id' => 1002, 'quantity' => 1],
        ],
    ],
    [
        'order_id' => 'B456',
        'items' => [
            ['product_id' => 1003, 'quantity' => 3],
            ['product_id' => 1004, 'quantity' => 1],
        ],
    ],
];

我們的目標是從每個訂單中提取出商品ID。可以使用array_column()函數進行提取。

提取商品ID代碼:

 $productIds = [];

foreach ($orders as $order) {
    $productIds[] = array_column($order['items'], 'product_id');
}

print_r($productIds);

結果輸出:

 Array
(
    [0] => Array
        (
            [0] => 1001
            [1] => 1002
        )
    [1] => Array
        (
            [0] => 1003
            [1] => 1004
        )
)

3. 提取所有商品ID為平面數組

如果你希望將所有訂單中的商品ID合併為一個平面數組,而不是保留每個訂單的數組結構,你可以使用array_merge()函數來實現:

 $productIds = [];

foreach ($orders as $order) {
    $productIds = array_merge($productIds, array_column($order['items'], 'product_id'));
}

print_r($productIds);

結果輸出:

 Array
(
    [0] => 1001
    [1] => 1002
    [2] => 1003
    [3] => 1004
)

通過上面的代碼,我們成功地提取了所有訂單中的商品ID,並將其合併成一個平面數組。

4. 使用URL作為訂單數據源(示例)

如果訂單數據來自遠程接口或者API,我們可以使用file_get_contents()或者cURL來獲取數據。例如,假設訂單數據來自一個API,URL為https://m66.net/api/orders ,我們可以通過以下代碼來獲取訂單數據並提取商品ID: