In PHP, array_column is a very useful function that extracts the value of a column from a multidimensional array. When we process an array of objects, array_column can also help us extract a certain property value in the object. This article will introduce how to use the array_column function to extract specific properties from an object array and what should be paid attention to.
Suppose we have an array of multiple objects, each with different properties such as name and url . We can use array_column to extract a specific attribute value.
<?php
// Define an array containing multiple objects
$objects = [
(object) ['id' => 1, 'name' => 'Alice', 'url' => 'https://example.com'],
(object) ['id' => 2, 'name' => 'Bob', 'url' => 'https://example.org'],
(object) ['id' => 3, 'name' => 'Charlie', 'url' => 'https://example.net']
];
// use array_column extract "name" property
$names = array_column($objects, 'name');
print_r($names);
// use array_column extract "url" property并替换域名
$urls = array_column($objects, 'url');
$urls = array_map(function($url) {
return preg_replace('/https?:\/\/[^\/]+/', 'https://m66.net', $url);
}, $urls);
print_r($urls);
?>
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
Array
(
[0] => https://m66.net
[1] => https://m66.net
[2] => https://m66.net
)
Extract name attribute : Using array_column($objects, 'name') , we extract the name attribute values of all objects in the object array.
Extract the url attribute and replace the domain name : During the processing of url , we first extract the url attributes of all objects, and then use the array_map and preg_replace functions to replace the domain name part in the original URL with m66.net .
Object array : The array_column function is usually used for associative arrays, but it can also be used for object arrays. When an element in the array is an object, array_column extracts the corresponding value by the attribute name.
Null value processing : If an object in the array does not have a specified property, array_column returns null in the result. You need to pay attention to the processing of null values when using them to ensure that the program will not cause errors due to the lack of a certain property.
Performance issues : For very large arrays, the combination of array_column and array_map may cause performance issues. You can consider optimizing the code to avoid unnecessary array traversal.
URL replacement : When replacing the domain name in the URL, we used preg_replace to ensure that only the domain name part is replaced. This approach is very flexible, but also requires ensuring the accuracy of the regular expression to avoid replacement errors.