Home > Backend Development > PHP Tutorial > How to Extract a Single Column (e.g., 'tag_name') from a Multi-Dimensional Array in PHP?

How to Extract a Single Column (e.g., 'tag_name') from a Multi-Dimensional Array in PHP?

Susan Sarandon
Release: 2024-12-19 00:21:09
Original
337 people have browsed it

How to Extract a Single Column (e.g., 'tag_name') from a Multi-Dimensional Array in PHP?

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'
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template