Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_column function

Returns the values corresponding to a specified column from the provided array.

Description / Descripción
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
Sintaxis / Sintax
$acolumn = array_column($array,$column_key,$index_key);
$acolumn = array_column($array,$column_key)
Please note that we are always talking about multidimensional arrays. For example, suppose we have a products array; we are directly referring to a table that will have the product, stock, price, and maybe the supplier’s ID—why not?

Parameters

$array – The array from which we will obtain our column.

$column_key – The column from which we will retrieve the data.

$index_key – This parameter is optional; if not specified, the index in the returned array will be numeric. If specified, it will be one of the columns from $array, and you will understand better when we look at the example.

Return

It returns an array with the values from the specified column.

Examples

Example 1

I have taken the example from php.net and modified it slightly so that we can see everything mentioned above easily:

Ejemplo de php.net modificado
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);
 
$first_names = array_column($records,'first_name','last_name');
print_r($first_names);
$first_names = array_column($records,'first_name','id');
print_r($first_names);
$first_names = array_column($records,'first_name');
print_r($first_names);
Array
(
    [Doe] => Peter
    [Smith] => Sally
    [Jones] => Jane
)
Array
(
    [2135] => John
    [3245] => Sally
    [5342] => Jane
    [5623] => Peter
)
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Ejemplo2 – Applying array_column to an SQL query.

Let’s suppose we have a database called “example_products” with the following table:

SQL
-- Crear la tabla 'productos'
CREATE TABLE productos (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nombre VARCHAR(255),
    precio DECIMAL(10, 2),
    descripcion TEXT,
    categoria VARCHAR(50)
);

-- Insertar 20 productos de ejemplo en la tabla 'productos'
INSERT INTO productos (nombre, precio, descripcion, categoria)
VALUES
    ('Producto 1', 19.99, 'Descripción del Producto 1', 'Electrónica'),
    ('Producto 2', 29.99, 'Descripción del Producto 2', 'Ropa'),
    ('Producto 3', 9.99, 'Descripción del Producto 3', 'Hogar'),
    ('Producto 4', 49.99, 'Descripción del Producto 4', 'Electrónica'),
    ('Producto 5', 14.99, 'Descripción del Producto 5', 'Ropa'),
    ('Producto 6', 39.99, 'Descripción del Producto 6', 'Hogar'),
    ('Producto 7', 24.99, 'Descripción del Producto 7', 'Electrónica'),
    ('Producto 8', 19.99, 'Descripción del Producto 8', 'Ropa'),
    ('Producto 9', 7.99, 'Descripción del Producto 9', 'Hogar'),
    ('Producto 10', 54.99, 'Descripción del Producto 10', 'Electrónica'),
    ('Producto 11', 12.99, 'Descripción del Producto 11', 'Ropa'),
    ('Producto 12', 34.99, 'Descripción del Producto 12', 'Hogar'),
    ('Producto 13', 29.99, 'Descripción del Producto 13', 'Electrónica'),
    ('Producto 14', 22.99, 'Descripción del Producto 14', 'Ropa'),
    ('Producto 15', 8.99, 'Descripción del Producto 15', 'Hogar'),
    ('Producto 16', 64.99, 'Descripción del Producto 16', 'Electrónica'),
    ('Producto 17', 17.99, 'Descripción del Producto 17', 'Ropa'),
    ('Producto 18', 42.99, 'Descripción del Producto 18', 'Hogar'),
    ('Producto 19', 31.99, 'Descripción del Producto 19', 'Electrónica'),
    ('Producto 20', 11.99, 'Descripción del Producto 20', 'Ropa');

How could we retrieve all the products from this table and filter them by one of its columns?

Ejemplo de array_column aplicado a una consulta MySQL
$dbconnection = new mysqli('localhost', 'root', '', 'example_products');
$resultado = $dbconnection->query("SELECT * FROM productos");
$arr = $resultado->fetch_all(MYSQLI_ASSOC);
$arr2 = array_column($arr,'nombre');
var_dump($arr2);
array(20) { [0]=> string(10) "Producto 1" [1]=> string(10) "Producto 2" [2]=> string(10) "Producto 3" [3]=> string(10) "Producto 4" [4]=> string(10) "Producto 5" [5]=> string(10) "Producto 6" [6]=> string(10) "Producto 7" [7]=> string(10) "Producto 8" [8]=> string(10) "Producto 9" [9]=> string(11) "Producto 10" [10]=> string(11) "Producto 11" [11]=> string(11) "Producto 12" [12]=> string(11) "Producto 13" [13]=> string(11) "Producto 14" [14]=> string(11) "Producto 15" [15]=> string(11) "Producto 16" [16]=> string(11) "Producto 17" [17]=> string(11) "Producto 18" [18]=> string(11) "Producto 19" [19]=> string(11) "Producto 20" }
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category