<?php
function __( $str ) {
return $str;
}
function _doing_it_wrong( $func, $error_message, $version ) {
trigger_error( $error_message, E_USER_NOTICE );
}
class WP_List_Util {
/**
* The input array.
*
* @since 4.7.0
* @var array
*/
private $input = array();
/**
* The output array.
*
* @since 4.7.0
* @var array
*/
private $output = array();
/**
* Temporary arguments for sorting.
*
* @since 4.7.0
* @var string[]
*/
private $orderby = array();
/**
* Constructor.
*
* Sets the input array.
*
* @since 4.7.0
*
* @param array $input Array to perform operations on.
*/
public function __construct( $input ) {
$this->output = $input;
$this->input = $input;
}
public function pluck( $field, $index_key = null ) {
$newlist = array();
if ( ! $index_key ) {
/*
* This is simple. Could at some point wrap array_column()
* if we knew we had an array of arrays.
*/
foreach ( $this->output as $key => $value ) {
if ( is_object( $value ) ) {
if ( property_exists( $value, $field ) ) {
$newlist[ $key ] = $value->$field;
}
} elseif ( is_array( $value ) ) {
if ( array_key_exists( $field, $value ) ) {
$newlist[ $key ] = $value[ $field ];
}
} else {
_doing_it_wrong(
__METHOD__,
__( 'Values for the input array must be either objects or arrays.' ),
'6.2.0'
);
}
}
$this->output = $newlist;
return $this->output;
}
/*
* When index_key is not set for a particular item, push the value
* to the end of the stack. This is how array_column() behaves.
*/
foreach ( $this->output as $value ) {
if ( is_object( $value ) ) {
if ( property_exists( $value, $field ) ) {
if ( property_exists( $value, $index_key ) ) {
$newlist[ $value->$index_key ] = $value->$field;
} else {
$newlist[] = $value->$field;
}
}
} elseif ( is_array( $value ) ) {
if ( array_key_exists( $field, $value ) ) {
if ( array_key_exists( $index_key, $value ) ) {
$newlist[ $value[ $index_key ] ] = $value[ $field ];
} else {
$newlist[] = $value[ $field ];
}
}
} else {
// _doing_it_wrong(
// __METHOD__,
// __( 'Values for the input array must be either objects or arrays.' ),
// '6.2.0'
// );
}
}
$this->output = $newlist;
return $this->output;
}
}
function wp_list_pluck( $input_list, $field, $index_key = null ) {
if ( ! is_array( $input_list ) ) {
return array();
}
$util = new WP_List_Util( $input_list );
return $util->pluck( $field, $index_key );
}
/*
* Test with an array of arrays.
*/
$input_list = array(
array( '123' => '456' ),
array( 'foo' => 'bar' ),
array( 'foo' => 'baz' ),
);
var_dump( array_column( $input_list, 'foo', null ) );
var_dump( wp_list_pluck( $input_list, 'foo', null ) );
/*
* Test with an array of objects.
*/
$input_list = array(
(object) array( '123' => '456' ),
(object) array( 'foo' => 'bar' ),
(object) array( 'foo' => 'baz' ),
);
var_dump( wp_list_pluck( $input_list, 'foo', null ) );
preferences:
31.88 ms | 407 KiB | 5 Q