How to quickly extract the product ID in an e-commerce order through PHP's array_column function?
In e-commerce development, when processing order information, we often need to extract specific data from the order array, such as product ID. PHP provides a very practical function array_column() , which can easily extract a column of data from a multidimensional array. This article will demonstrate through examples how to use the array_column() function to quickly extract the product ID in the e-commerce order.
The array_column() function is an array operation function built in PHP, which is used to extract data from a column of the data from a multi-dimensional array. The basic syntax of this function is as follows:
array_column(array $input, mixed $column_key, mixed $index_key = null): array
$input : The input array to be operated on.
$column_key : Extracted column name (can be the key name of the array).
$index_key : Optional, index of the result array.
This function returns an array containing the extracted columns.
Suppose we have a set of e-commerce order data, each order contains multiple items, and our goal is to extract the IDs of these items.
$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],
],
],
];
Our goal is to extract the item ID from each order. You can use the array_column() function to extract it.
$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
)
)
If you want to merge the item IDs in all orders into a flat array instead of keeping the array structure of each order, you can use the array_merge() function to implement it:
$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
)
Through the above code, we successfully extracted the item IDs in all orders and merged them into a flat array.
If the order data comes from a remote interface or API, we can use file_get_contents() or cURL to get the data. For example, suppose the order data comes from an API with the URL https://m66.net/api/orders , we can get the order data and extract the item ID through the following code: