Retrieving a Single Column from a Multi-Dimensional Array
Retrieving a specific column from a multi-dimensional array can be a common task in many programming scenarios. In this case, the objective is to extract a comma-separated string of values from the "tag_name" key of an array.
To achieve this effect, we can employ the implode() function, which combines array elements into a string using a specified separator. To extract the desired values, we will first use the array_map() function to create a new array containing only the "tag_name" values.
Here's the solution using array_map():
$input = [ [ 'tag_name' => 'google' ], [ 'tag_name' => 'technology' ] ]; $tagNames = array_map(function ($entry) { return $entry['tag_name']; }, $input); echo implode(', ', $tagNames); // 'google, technology'
In PHP 5.5.0 and later, we can also use the more concise array_column() function:
echo implode(', ', array_column($input, 'tag_name')); // 'google, technology'
The above is the detailed content of How to Extract a Single Column (e.g., 'tag_name') from a Multi-Dimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!