我有以下PHP函数来获取一些user_ids,我希望将其作为收件人添加到消息中,如下所示。
function true_my_bp_get_users_by_xprofile( $field_id_to_check, $num_to_find ) {
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check,
$num_to_find
)
);
print_r($user_ids);
}
我正在使用true_my_bp_get_users_by_xprofile( 5, 18 );
打印Array ( [0] => stdClass Object ( [user_id] => 1 ) [1] => stdClass Object ( [user_id] => 2 ) )
然后我有一个包含以下代码的HTML表单:
$body_input=isset($_POST['body_input'])?$_POST['body_input']:'';
$subject_input=isset($_POST['subject_input'])?$_POST['subject_input']:'';
send_msg( $user_ids,$body_input, $subject_input);
send_msg
function send_msg($user_id, $title, $message){
$args = array( 'recipients' => $user_id, 'sender_id' => bp_loggedin_user_id(), 'subject' => $title, 'content' => $message );
messages_new_message( $args );
}
我想做什么:
从$user_ids
获取数组并将其放在此处:'recipients' => $user_id
我尝试在函数中用$ user_ids替换$ user_id,但它不起作用。
答案 0 :(得分:1)
由于您将数据放在函数内的$user_ids
变量中,因此其范围仅限于该函数。可以通过几种不同的方式在函数外部存储和访问数据。
1)。通过引用将变量传递给true_my_bp_get_users_by_xprofile
。
$user_ids = null;
function true_my_bp_get_users_by_xprofile( $field_id_to_check, $num_to_find, &$user_ids ) {
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check,
$num_to_find
)
);
print_r($user_ids);
}
调用函数
true_my_bp_get_users_by_xprofile( 5, 18, $user_ids );
现在您的$user_ids
拥有数据并且可以在函数外部访问。
2)。从$user_ids
函数
true_my_bp_get_users_by_xprofile
function true_my_bp_get_users_by_xprofile( $field_id_to_check, $num_to_find ) {
global $wpdb;
$table_name = $wpdb->prefix . "bp_xprofile_data";
$user_ids = $wpdb->get_results(
$wpdb->prepare(
"SELECT user_id FROM $table_name
WHERE field_id = %d AND value LIKE '%%\"%d\"%%'",
$field_id_to_check,
$num_to_find
)
);
print_r($user_ids);
return $user_ids;
}
调用函数就好 $ user_ids = true_my_bp_get_users_by_xprofile(5,18);
现在,您可以在上面的代码中调用send_msg
函数,即
send_msg( $user_ids, $body_input, $subject_input);