我编写了包含许多update\\u post\\u元条目的代码:
update_post_meta($order_id, \'_shipping_first_name\', $order->get_billing_first_name() );
update_post_meta($order_id, \'_shipping_last_name\', $order->get_billing_last_name() );
update_post_meta($order_id, \'_shipping_company\', $order->get_billing_company() );
update_post_meta($order_id, \'_shipping_address_1\', $order->get_billing_address_1() );
update_post_meta($order_id, \'_shipping_address_2\', $order->get_billing_address_2() );
update_post_meta($order_id, \'_shipping_postcode\', $order->get_billing_postcode() );
update_post_meta($order_id, \'_shipping_city\', $order->get_billing_city() );
update_post_meta($order_id, \'_shipping_state\', $order->get_billing_state() );
update_post_meta($order_id, \'_shipping_country\', $order->get_billing_country() );
对于DRY原则,我尝试使用带有For循环的数组,但它不起作用:
$data = array(
array( \'_shipping_first_name\', $order->get_billing_first_name() ),
array( \'_shipping_last_name\', $order->get_billing_last_name() ),
array( \'_shipping_company\', $order->get_billing_company() ),
array( \'_shipping_address_1\', $order->get_billing_address_1() ),
array( \'_shipping_address_2\', $order->get_billing_address_2() ),
array( \'_shipping_postcode\', $order->get_billing_postcode() ),
array( \'_shipping_city\', $order->get_billing_city() ),
array( \'_shipping_state\', $order->get_billing_state() ),
array( \'_shipping_country\', $order->get_billing_country() )
);
for ( $row = 0; $row < 9; $row++) {
for ( $col = 0; $col < 2; $col++) {
update_post_meta( $order_id, [$row], [$col] );
}
}
最合适的回答,由SO网友:Paul G. 整理而成
为了达到您想要的效果,您最好创建一个关联数组,然后使用foreach
循环如下所示:
$data = array(
\'_shipping_first_name\' => $order->get_billing_first_name(),
\'_shipping_last_name\' => $order->get_billing_last_name(),
\'_shipping_company\' => $order->get_billing_company(),
\'_shipping_address_1\' => $order->get_billing_address_1(),
\'_shipping_address_2\' => $order->get_billing_address_2(),
\'_shipping_postcode\' => $order->get_billing_postcode(),
\'_shipping_city\' => $order->get_billing_city(),
\'_shipping_state\' => $order->get_billing_state(),
\'_shipping_country\' => $order->get_billing_country()
);
foreach ( $data as $meta_key => $meta_value ) {
update_post_meta( $order_id, $meta_key, $meta_value );
}