I am running two queries, they return arrays similar to what is shown below:
First:
array(
array(
'id' => 1
),
array(
'id' => 2
),
array(
'id' => 3
),
array(
'id' => 4
),
)
Second:
array(
array(
'id' => 4
),
array(
'id' => 5
),
array(
'id' => 6
),
array(
'id' => 7
),
)
But I want to end up with
$ids = array(1,2,3,4,5,6,7);
But the only way I can think of to do that is
$ids = array();
foreach(array($array1, $array2) as $a){
foreach($a as $id){
$ids[] = $id['id'];
}
}
$ids = array_unique($ids);
But that doesn't seem very efficient to me, and with the wealth of array functions out there, I am wondering if there is a better way?
Not sure if this is what you are looking for but try:
Probably not as your arrays are associative but at least you can skip some of your steps.
There would be a few ways to handle this. I think I would probably start with
array_merge()
on the two original arrays, then flatten it witharray_map()
, and finally callarray_unique()
.Better: Do it in one query.
After seeing the query, these do not need to be two arrays. It can be done with a single
UNION
query. Using a plainUNION
instead of aUNION ALL
will deduplicate them for you.When fetching rows, since you have only one column, you may consider directly flattening it in the fetch.