I am making looped queries on my wp_bp_friends
database table and returning an array of single-property objects each time. I would like to merge all of these values into a single flat array then implode with commas.
My current code:
foreach ( $friendsid as $row )
{
$sql1= "SELECT friend_user_id
FROM wp_bp_friends
WHERE initiator_user_id='".$row->friend_user_id."'
AND is_confirmed = 1";
$ffid = $wpdb->get_results($sql1);
// $recur_multi_dimen_arr_obj = new RecursiveArrayIterator($ffid);
// $recur_flat_arr_obj = new RecursiveIteratorIterator($recur_multi_dimen_arr_obj);
// $flat_arr = iterator_to_array($recur_flat_arr_obj, false);
// print_r($flat_arr);
print_r($ffid);
}
It outputs the following
Array(
[0] => stdClassObject([friend_user_id] => 62)
[1] => stdClassObject([friend_user_id] => 51)
[2] => stdClassObject([friend_user_id] => 60)
[3] => stdClassObject([friend_user_id] => 65)
[4] => stdClassObject([friend_user_id] => 56)
)
Array(
[0] => stdClassObject([friend_user_id] => 43)
[1] => stdClassObject([friend_user_id] => 50)
[2] => stdClassObject([friend_user_id] => 64)
[3] => stdClassObject([friend_user_id] => 45)
[4] => stdClassObject([friend_user_id] => 44)
)
Array(
[0] => stdClassObject([friend_user_id] => 57)
)
Using
$resultarray = array();
foreach($ffid as $oneitem){
$resultarray[]=$oneitem->friend_user_id;
}
$excluded_user =implode(", ",$resultarray);
I get:
$excluded_user = 57;
What I need to end up with is
$excluded_user = '62, 51, 60, 65, 56, 43, 50, 64, 45, 44, 57;
How can I combine the arrays in $ffid before I use the foreach loop?
Note that the number of arrays in $ffid can vary.
The functions
array_map
andarray_walk_recursive
do the trick. A standalone code sample follows:You could use array_merge function, to create an array which includes all the data.
Something like this:
array_map and array_merge seems to be a good choice for this
Use this code:
Some thing like this
First and foremost, you should not be making multiple trips to the database for this payload of data. You should be passing your array of friend ids to a prepared statement which contains a dynamically populated string of delimited question marks (e.g.
initiator_user_id IN (?,?,?)
). I even have a demonstration of how to do this with WordPress helpers.I don’t use WordPress, but I assume
get_col()
is the ideal helper method to isolate the results.