在woocommerce中,我试图从高级自定义字段(ACF)中获取多维数组中的数据,以填充woocommerce_form_field()
选择字段选项。
如果我print_r
数据来自:
$pickup = get_field_object('pick_up', 'pick_up_list')['value'];
我有这个:
Array
(
[0] => Array
(
[name] => Hotel Cla
[price] => 0
)
[1] => Array
(
[name] => Ritz Carlon
[price] => 7
)
)
然后,我在使用此数组时收到错误Array to string conversion in
:
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $pickup
));
我想要的是能够将$pickup
数组添加为选择字段。有什么帮助吗?
答案 0 :(得分:1)
选项应该是关联数组键=>值,试试这个:
$options = array();
foreach($pickup as $index => $values) {
$options[$index] = $values['name'];
}
然后,调用函数:
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $options
));
答案 1 :(得分:1)
也可以在简单的FOR
循环中完成,将'name'
和'price'
值保持为<option>
提交的值:
$pickup = get_field_object('pick_up', 'pick_up_list')['value'];
$options = array();
for( $i = 0; $i < count($pickup); $i++ ){
$options[$pickup[$i]['name'].'_'.$pickup[$i]['price']] = $pickup[$i]['name'];
}
woocommerce_form_field( 'pick_up_list', array(
'type' => 'select',
'class' => array('form-row-wide'),
'label' => __('Pick Up'),
'options' => $options
));
然后,一旦提交了数据,您就可以通过这种方式获得'name'
和'price'
:
if( isset($_POST['pick_up_list']) ){
$pick_up_list = sanitize_text_field($_POST['pick_up_list']);
$pick_up_list = explode('_', $pick_up_list); // Separate the merged data
$name = $pick_up_list[0]; // The hotel name
$price = $pick_up_list[1]; // The hotel price
}