wp_list_pluck()取一个数组中的指定列

目录

描述

Pluck a certain field out of each object in a list

wp_list_pluck() 描述

用法

<?php wp_list_pluck$list$field$index_key null ); ?>

wp_list_pluck() 用法

参数

$list

(array) (必填) A list of objects or arrays

默认值: None

$field

(mixed) (必填) A field from the object to place instead of the entire object

默认值: None

$index_key

(mixed) (可选) Field from the object to use as keys for the new array. Added in 4.0

默认值: null

wp_list_pluck() 参数

返回值

(array

Array of found values. If $index_key is set, an array of found values with keys corresponding to $index_key.

wp_list_pluck() 返回值

示例

The following is an array listing foods:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
$foods = array(
	array(
		'id'  => 4,
		'name'  => 'Banana',
		'color' => 'Yellow',
	),
	array(
		'id'  => '5',
		'name'  => 'Apple',
		'color' => 'Red',
	),
	array(
		'id'  => 2,
		'name'  => 'Lettuce',
		'color' => 'Green',
	),
	array(
		'id'  => '7',
		'name'  => 'Apple',
		'color' => 'Red',
	),
);
?>

The names of each food can easily be "plucked" from the $foods array using
wp_list_pluck().

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php $food_names = wp_list_pluck( $foods, 'name' ); ?>

$food_names will now contain a numerically indexed array of food names equivalent to:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
array(
	'Banana',
	'Apple',
	'Lettuce',
	'Apple'
);
?>

Since version 4.0 you may define a third parameter named $index_key to define a specific field of the list to be used as key. The following snippet would get listings in the form of id => name.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php $food_names = wp_list_pluck( $foods, 'name', 'id' ); ?>

The resulting $food_names array:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
array(
	4 => 'Banana',
	5 => 'Apple',
	2 => 'Lettuce',
	7 => 'Apple'
);
?>

wp_list_pluck() 示例

历史

添加于 版本: 3.1

wp_list_pluck() 历史