在電商開發中,處理訂單信息時我們經常需要從訂單數組中提取特定的數據,比如商品ID。 PHP提供了一個非常實用的函數array_column() ,它可以輕鬆地從多維數組中提取某一列數據。本文將通過實例演示如何使用array_column()函數來快速提取電商訂單中的商品ID。
array_column()函數是PHP 內建的一個數組操作函數,它用於從多維數組中提取出某一列的數據。該函數的基本語法如下:
array_column(array $input, mixed $column_key, mixed $index_key = null): array
$input : 需要操作的輸入數組。
$column_key : 提取的列名(可以是數組的鍵名)。
$index_key : 可選,結果數組的索引。
這個函數返回一個包含所提取列的數組。
假設我們有一組電商訂單數據,每個訂單包含多個商品,我們的目標是提取出這些商品的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()函數進行提取。
$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
)
)
如果你希望將所有訂單中的商品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,並將其合併成一個平面數組。
如果訂單數據來自遠程接口或者API,我們可以使用file_get_contents()或者cURL來獲取數據。例如,假設訂單數據來自一個API,URL為https://m66.net/api/orders ,我們可以通過以下代碼來獲取訂單數據並提取商品ID: