从数组中为每个循环构建简单的PHP
I have an array called $user_ids
that prints as:
Array ( [0] => stdClass Object ( [user_id] => 1 ) [1] => stdClass Object ( [user_id] => 2 ) )
I want to perform send_msg
for every user_id
in the array. In the example above, I want to achieve the equivalent of this:
send_msg( 1, $body_input, $subject_input);
send_msg( 2, $body_input, $subject_input);
This is what I have tried but it doesn't work.
foreach ($user_ids as $user_N){
send_msg( $user_N, $body_input, $subject_input);
}
我有一个名为 我想为数组中的每个 这是我尝试过但它不起作用。 p>
$ user_ids code>的数组,打印为: p>
数组([0] => stdClass对象([user_id] => 1)[1] => stdClass对象([user_id] => 2))
code > pre>
user_id code>执行
send_msg code>。 在上面的例子中,我想实现相当于: p>
send_msg(1,$ body_input,$ subject_input);
send_msg(2,$ body_input,$ subject_input);
code> pre>
foreach($ user_ids as $ user_N){
send_msg($ user_N,$ body_input,$ subject_input);
}
code> pre>
div>
In PHP >= 7.0.0 you can extract all of the user_id
s from the objects with array_column
:
foreach(array_column($user_ids, 'user_id') as $user_N) {
send_msg($user_N, $body_input, $subject_input);
}
<?php
// You're looping over objects; not user IDs
foreach ($user_ids as $obj){
send_msg( $obj->user_id, $body_input, $subject_input);
}
?>
You have an array with objects. To get the ID in your loop, you must use $user_N->user_id
so change your loop to:
foreach ($user_ids as $user_N){
send_msg( $user_N->user_id, $body_input, $subject_input);
}
looks like you converted a JSON to ARRAY without passing second parameter to true and that is why you have array of objects.
http://php.net/manual/en/function.json-decode.php
In this case you can do
send_msg( $user_N->user_id, $body_input, $subject_input);
But if you convert JSON to associated array(by passing second param to true), then you can do
send_msg( $user_N['user_id'], $body_input, $subject_input);