我过去也有类似的需求array destructing
@phatskat提到我创建了一个助手函数来完成循环。
辅助函数,
function get_keyed_meta_data_array( int $post_id, array $keys ) {
$keyed_meta = array();
$post_meta = get_post_meta( $post_id, \'\', true );
foreach ( $keys as $key ) {
if ( isset( $post_meta[$key] ) ) {
$keyed_meta[$key] = $post_meta[$key];
} else {
$keyed_meta[$key] = \'\';
}
}
return $keyed_meta;
}
用途,
$keys = array(
\'image\',
\'car_year\',
\'car_mileage\',
\'car_price\',
\'car_model\'
); // key array could also be returned from a config function for DRY purposes
$data = get_keyed_meta_data_array( $post->ID, $keys );
// $data[\'car_year\'] = 2019;
// $data[\'car_mileage\'] = 123;
// $data[\'car_model\'] = \'\';