迭代get_post_meta()结果

时间:2022-01-03 作者:Foysal

我有如下WordPress代码。

function get_preselect_values()
{
    $volunteers = get_post_meta($_POST[\'element_id\'], "volunteers", false);
    $users = array();
    
    foreach ($volunteers as $volunteer) {
        foreach ($volunteer as $volun) {
            $users = $volun[\'ID\'];
        }
    }
    echo json_encode($users);
    die;
}

add_action(\'wp_ajax_get_preselect_values\', \'get_preselect_values\');
add_action(\'wp_ajax_nopriv_get_preselect_values\', \'get_preselect_values\');
我只得到First 价值

如何获取所有值?

2 个回复
最合适的回答,由SO网友:Pat J 整理而成

您正在破坏$users 数组的每次迭代foreach 环要向数组中添加新项,应使用$users[] = {...}, 不$users = {...}.

function get_preselect_values()
{
    $volunteers = get_post_meta($_POST[\'element_id\'], "volunteers", false);
    $users = array();
    
    foreach ($volunteers as $volunteer) {
        foreach ($volunteer as $volun) {
            $users[] = $volun[\'ID\'];
        }
    }
    echo json_encode($users);
    die;
}

add_action(\'wp_ajax_get_preselect_values\', \'get_preselect_values\');
add_action(\'wp_ajax_nopriv_get_preselect_values\', \'get_preselect_values\');

SO网友:Sébastien Serre

你能解释一下是什么吗display_number? 我没有看到有这个名字的钥匙?

一个简单的foreach 例如:

foreach ( $volunteers as $volunteer) {
    echo $volunteer[\'ID\'];
}
例如,将显示志愿者ID。

相关推荐