Php array column to key

array_column

array_column() возвращает массив из значений столбца массива array с ключом column_key . Опционально можно указать index_key , чтобы индексировать возвращаемый массив значениями из столбца с ключом index_key входного массива.

Список параметров

Многомерный массив или массив объектов, из которого будет производиться выборка значений. Если задан массив объектов, то можно выбирать любые его общедоступные свойства. Для выборки закрытых или защищенных свойств, объект должен реализовывать магические методы __get() и __isset() .

Ключ столбца, значения которого нужно вернуть. Может содержать как числовой ключ, так и строковой для ассоциативных массивов. А также может принимать значение null , тогда возвращаются не значения определенного столбца, а весь массив (полезно использовать вместе с index_key чтобы переиндексировать массив).

Ключ столбца, значения которого будут использоваться в качестве ключей возвращаемого массива. Может быть как целочисленным ключом, так и строковым. Тип значения приводится, как обычно для ключей массива (однако, объекты, поддерживающие преобразование к строке также разрешены).

Возвращаемые значения

Возвращает массив из значений одного столбца входного массива (набора записей).

Список изменений

Версия Описание
7.0.0 Добавлена возможность использовать массив объектов в array .

Примеры

Пример #1 Получим столбец с именами из набора записей

// Массив, представляющий из себя набор записей полученных из базы данных
$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’ );
print_r ( $first_names );
?>

Результат выполнения данного примера:

Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )

Пример #2 Получим столбец с фамилиями, а в качестве ключей возвращаемого массива используем значения из столбца «id»

// Используем массив $records из первого примера
$last_names = array_column ( $records , ‘last_name’ , ‘id’ );
print_r ( $last_names );
?>

Результат выполнения данного примера:

Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )

Пример #3 Получим столбец имен пользователей из общедоступного свойства «username» объекта

class User
public $username ;

public function __construct ( string $username )
$this -> username = $username ;
>
>

$users = [
new User ( ‘user 1’ ),
new User ( ‘user 2’ ),
new User ( ‘user 3’ ),
];

print_r ( array_column ( $users , ‘username’ ));
?>

Результат выполнения данного примера:

Array ( [0] => user 1 [1] => user 2 [2] => user 3 )

Пример #4 Получим столбец имен пользователей из приватного свойства «name» объекта, используя магический метод __get() .

Читайте также:  Css animation show text

class Person
private $name ;

public function __construct ( string $name )
$this -> name = $name ;
>

public function __get ( $prop )
return $this -> $prop ;
>

public function __isset ( $prop ) : bool
return isset( $this -> $prop );
>
>

$people = [
new Person ( ‘Fred’ ),
new Person ( ‘Jane’ ),
new Person ( ‘John’ ),
];

print_r ( array_column ( $people , ‘name’ ));
?>

Результат выполнения данного примера:

Array ( [0] => Fred [1] => Jane [2] => John )

Источник

array_column

array_column() returns the values from a single column of the array , identified by the column_key . Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

Parameters

A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be null to return complete arrays or objects (this is useful together with index_key to reindex the array).

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys (however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed).

Return Values

Returns an array of values representing a single column from the input array.

Changelog

Version Description
8.0.0 Objects in columns indicated by index_key parameter will no longer be cast to string and will now throw a TypeError instead.

Examples

Example #1 Get the column of first names from a recordset

// 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’ );
print_r ( $first_names );
?>

The above example will output:

Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )

Example #2 Get the column of last names from a recordset, indexed by the «id» column

Читайте также:  Базовый калькулятор на java

// Using the $records array from Example #1
$last_names = array_column ( $records , ‘last_name’ , ‘id’ );
print_r ( $last_names );
?>

The above example will output:

Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )

Example #3 Get the column of usernames from the public «username» property of an object

class User
public $username ;

public function __construct ( string $username )
$this -> username = $username ;
>
>

$users = [
new User ( ‘user 1’ ),
new User ( ‘user 2’ ),
new User ( ‘user 3’ ),
];

print_r ( array_column ( $users , ‘username’ ));
?>

The above example will output:

Array ( [0] => user 1 [1] => user 2 [2] => user 3 )

Example #4 Get the column of names from the private «name» property of an object using the magic __get() method.

class Person
private $name ;

public function __construct ( string $name )
$this -> name = $name ;
>

public function __get ( $prop )
return $this -> $prop ;
>

public function __isset ( $prop ) : bool
return isset( $this -> $prop );
>
>

$people = [
new Person ( ‘Fred’ ),
new Person ( ‘Jane’ ),
new Person ( ‘John’ ),
];

print_r ( array_column ( $people , ‘name’ ));
?>

The above example will output:

Array ( [0] => Fred [1] => Jane [2] => John )
  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Understanding the PHP Function array_column()

    The PHP function array_column() is a handy tool for extracting values from arrays, and transforming them into new arrays. It is often used when dealing with multi-dimensional arrays, and can help simplify the process of manipulating data. In this article, we’ll delve into the specifics of array_column() and show you how to use it in your own PHP projects.

    What is the array_column() Function?

    The array_column() function is a PHP built-in function that is used to extract values from an array, and return them as a new array. It takes two required parameters: the array that you want to extract values from, and the key (or column) that you want to extract. The function returns a new array that contains only the values from the specified column.

    Here’s the basic syntax of the array_column() function:

    array_column(array, column_key, [index_key]);
    • array : This is the array that you want to extract values from.
    • column_key : This is the key (or column) that you want to extract.
    • index_key (optional): This is the key that you want to use as the index (or key) of the returned array.

    How to Use the array_column() Function

    Using the array_column() function is quite simple. All you need to do is pass in an array and the key that you want to extract. Here’s an example that demonstrates how to use array_column() :

     $data = [ [ 'id' => 1, 'name' => 'John', 'age' => 30, ], [ 'id' => 2, 'name' => 'Jane', 'age' => 25, ], [ 'id' => 3, 'name' => 'Jim', 'age' => 35, ], ]; $names = array_column($data, 'name'); print_r($names); ?>

    The output of this code would be:

    Array ( [0] => John [1] => Jane [2] => Jim )

    In this example, the array_column() function has extracted the values from the name column and returned them as a new array.

    Using the index_key Parameter

    The index_key parameter allows you to specify a key to use as the index of the returned array. Here’s an example that demonstrates how to use the index_key parameter:

     $data = [ [ 'id' => 1, 'name' => 'John', 'age' => 30, ], [ 'id' => 2, 'name' => 'Jane', 'age' => 25, ], [ 'id' => 3, 'name' => 'Jim', 'age' => 35, ], ]; $names = array_column($data, 'name', 'id'); print_r($names); ?>

    The output of this code would be:

    Array ( [1] => John [2] => Jane [3] => Jim )

    In this example, the array_column() function has extracted the values from the name column, and used the id column as the index of the returned array.

    Use Cases for array_column()

    The array_column() function can be used in a variety of situations where you need to extract values from arrays and return them as a new array. Here are a few common use cases:

    • Extracting values from multi-dimensional arrays to create a simple list
    • Creating an associative array from a multi-dimensional array
    • Transforming a multi-dimensional array into a single-dimensional array for use in a drop-down list or other form element

    Conclusion

    In conclusion, the array_column() function is a powerful tool for extracting values from arrays and transforming them into new arrays. Whether you’re working with multi-dimensional arrays or simply need to extract specific values, array_column() can simplify your code and help you get the results you need.

    Источник

Оцените статью