将数组变量转换为另一个函数变量
我有以下PHP函数来获取某些user_id,然后我想按照以下方式将其作为收件人添加到消息中。将数组变量转换为另一个函数变量
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_ID user_ids,但它不工作。
由于您正在将数据放入函数中的$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
具有的功能之外的数据和accessable。 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);
真的很有意思,谢谢。我想他们不必是两个独立的功能。如果我把'send_msg'放入'true_my_bp_get_users_by_xprofile'中,会不会有更好的方法呢?虽然我不知道该怎么做。 https://pastebin.com/irCZ8iXe这是完整的代码,目前有点麻烦。 – redditor
您可以从第一个调用'send_msg'函数,但是您必须将'$ body_input'和'$ subject_input'传递给第一个变量,或者使用'global'来访问它,依此类推。我认为返回'$ user_ids'是最好的方法。 – Junaid
谢谢,我去了第二个。 – redditor
作为一个很好的做法; '全球'变量是一个不好的习惯。将类中的逻辑包装起来,使$ wpdb成为私有类属性。我知道WP允许这样做。另外,插件是否已经不存在这个功能? '不要重新发明轮子'。 –