What I'm trying to do is preserve the order of an array, while determining if each of the numbers match numbers that were pulled from the database. What I have is an array of numbers ($ids), and a non empty array of rows ($rows)
$images = array();
$ids = array(
0 => '41',
1 => '42',
2 => '43',
3 => '44'
);
// database example
$rows = array(
0 => array(
'name' => 'John Doe',
'id' => '42'
),
1 => array(
'name' => 'Jane Doe',
'id' => '43'
),
);
$i = 0;
foreach ($rows as $row) {
// This works, but it doesn't preserve the order of the $ids array
if (in_array($row['id'], $ids[$i])) {
// add $id to a new array
// or use the same $id array
$images[$i]['name'] = $row['name'];
$images[$i]['id'] = $row['id'];
$i ;
}
}
Any help would be appreciated.
CodePudding user response:
Since id is unique in the rows from your database, you can index the $rows
array by id to make it easier to look up values there. You can do this with array_column
like this:
$rows = array_column($rows, null, 'id');
Or add them to $rows
using id as index as you fetch them from the db like this:
while ($row = //whatever query result/prepared statement fetch you're using) {
$rows[$row['id']] = $row;
}
Then, instead of iterating $rows
, you can iterate $ids
. This will ensure that the resulting $images
array will be in the same order as $ids
.
foreach ($ids as $id) {
if (isset($rows[$id])) {
$images[] = [
'name' => $rows[$id]['name'],
'id' => $rows[$id]['id']
];
}
}
Another thing that might make this easier (unless you're using the non-matching rows for something else), would be to use the $ids
array as a parameter to a WHERE id IN
clause in the query that's selecting $rows
, so you won't have to do that filtering in PHP. Here's a Q&A that shows how to do that with PDO, for example: PHP - Using PDO with IN clause array.
CodePudding user response:
You could iterate over ids array instead. It will be something like this:
foreach($ids as $id) {
$data = find($id, $rows);
if ($data === null) {
continue;
}
$images[] = [
'name' => $data['name'],
'id' => $data['id']
];
}
function find($id, $rows) {
foreach($rows as $row) {
if($row['id'] == $id) {
return $row;
}
}
return null;
}
Totally agree with @Don't Panic, you should fetch only the data you'll use if possible.