Home >Backend Development >PHP Tutorial >How Can I Extract a Specific Column from a Multidimensional Array in PHP?

How Can I Extract a Specific Column from a Multidimensional Array in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-29 00:32:09765browse

How Can I Extract a Specific Column from a Multidimensional Array in PHP?

Extracting Array Columns in PHP

Original Question: Is there a function to extract a 'column' from an array in PHP?

Scenario:

Consider an array of arrays structured as follows:

array(
    array('page' => 'page1', 'name' => 'pagename1'),
    array('page' => 'page2', 'name' => 'pagename2'),
    array('page' => 'page3', 'name' => 'pagename3')
)

The goal is to obtain a new array that contains only the values of the 'name' keys:

array('pagename1', 'pagename2', 'pagename3')

Solution:

Since PHP 5.5

PHP 5.5 introduced the array_column() function, which is ideally suited for this task:

$samples = array(
    array('page' => 'page1', 'name' => 'pagename1'),
    array('page' => 'page2', 'name' => 'pagename2'),
    array('page' => 'page3', 'name' => 'pagename3')
);

$names = array_column($samples, 'name');

print_r($names); // ['pagename1', 'pagename2', 'pagename3']

This code uses array_column() to extract the 'name' column from the $samples array, resulting in the desired output.

The above is the detailed content of How Can I Extract a Specific Column from a Multidimensional Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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