Array column php многомерный массив

How to Get Values from Multi-dimensional Arrays with array_column()

array_column() is an inbuilt PHP function which can be used to get the values from a single column from the given multi-dimensional array or an array of objects.

Syntax

Support: (PHP 5>=5.5.0, PHP 7)

Parameters for array_column()

$input

  • The first parameter is mandatory.
  • It should be a multi-dimensional array or an array of objects from which to fetch/retrieve a column of values from.
  • With an array of objects, public properties can be directly fetched.
  • Whereas for protected or private properties, the class must implement both the __get() and __isset() methods.

$column_key

  • The second parameter is also mandatory.
  • It should be the column key for which values are to be fetched from a multi-dimensional array or an array of objects.
  • 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 for an array of objects.

$index_key

  • The third parameter is an optional one.
  • The column whose values are used as the index/keys for the returned/resulting array.
  • This value may be the integer key of the column, or it may be the string key name.
Читайте также:  Css border size code

Return Type

The return type of array_column() function is an another resultant array.

array_column() function returns a 1-D array which contains values from a single column of the given array, which is identified by a column_key.

Optionally, an index_key may also be provided to index the values in the resulted array by the values from the index_key column of the given array.

Example #1 Get the column of countries from a record-set

A good programming technique is trying to avoid the use of loops, nested loops & callback functions. The array_column() helps to reduce the code complexity and increases the code readability.

For more refer to the official documentation for same in manual.

Hope you find this helpful.

Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Источник

array_column

array_column() returns the values from a single column of the input , 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.

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

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.

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

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

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

Версия Описание
7.0.0 Added the ability for the input parameter to be an array of objects.

Примеры

Пример #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 );
?>

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

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

Пример #2 Get the column of last names from a recordset, indexed by the «id» column

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

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

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

Пример #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’ ));
?>

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

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

Пример #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’ ));
?>

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

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

Источник

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() .

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 )

Источник

PHP Функция array_column()

// Массив, представляющий возможный набор записей, возвращаемый из базы данных
$a = array(
array(
‘id’ => 5698,
‘first_name’ => ‘Андрей’,
‘last_name’ => ‘Щипунов’,
),
array(
‘id’ => 4767,
‘first_name’ => ‘Татьяна’,
‘last_name’ => ‘Щипунова’,
),
array(
‘id’ => 3809,
‘first_name’ => ‘Кристина’,
‘last_name’ => ‘Щипунова’,
)
);

$last_names = array_column($a, ‘last_name’);
print_r($last_names);
?>

Определение и использование

Функция array_column() возвращает значения из одного столбца входного массива.

Синтаксис

Параметр значений

Параметр Описание
array Требуемый. Задает используемый многомерный массив (набор записей). Начиная с PHP 7.0, это также может быть массив объектов.
column_key Требуемый. Целочисленный ключ или строковое имя возвращаемого столбца значений. Этот параметр также может быть NULL для возврата полных массивов (полезно вместе с index_key переиндексировать массив)
index_key Необязательный. Столбец, используемый в качестве индекса/ключей для возвращаемого массива

Технические подробности

Возврат значения: Возвращает массив значений, представляющий один столбец из входного массива
PHP Версия: 5.5+

Еще примеры

Пример

Получить столбец фамилий из набора записей, индексированного столбцом «id»:

// Массив, представляющий возможный набор записей, возвращаемый из базы данных
$a = array(
array(
‘id’ => 5698,
‘first_name’ => ‘Андрей’,
‘last_name’ => ‘Щипунов’,
),
array(
‘id’ => 4767,
‘first_name’ => ‘Татьяна’,
‘last_name’ => ‘Щипунова’,
),
array(
‘id’ => 3809,
‘first_name’ => ‘Кристина’,
‘last_name’ => ‘Щипунова’,
)
);

$last_names = array_column($a, ‘last_name’, ‘id’);
print_r($last_names);
?>

Мы только что запустили
SchoolsW3 видео

ВЫБОР ЦВЕТА

colorpicker

Сообщить об ошибке

Если вы хотите сообщить об ошибке или внести предложение, не стесняйтесь отправлять на электронное письмо:

Ваше предложение:

Спасибо Вам за то, что помогаете!

Ваше сообщение было отправлено в SchoolsW3.

ТОП Учебники
ТОП Справочники
ТОП Примеры
Получить сертификат

SchoolsW3 оптимизирован для бесплатного обучения, проверки и подготовки знаний. Примеры в редакторе упрощают и улучшают чтение и базовое понимание. Учебники, ссылки, примеры постоянно пересматриваются, чтобы избежать ошибок, но не возможно гарантировать полную правильность всего содержания. Некоторые страницы сайта могут быть не переведены на РУССКИЙ язык, можно отправить страницу как ошибку, так же можете самостоятельно заняться переводом. Используя данный сайт, вы соглашаетесь прочитать и принять Условия к использованию, Cookies и политика конфиденциальности.

Источник

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