Lets say there is an array $filter_from_array_id = array(2,8,52,45,7)
And then there is another array
$main_array = array([0] => array(id=> 8,name => 'data-ryhryh'),[1] => array(id=> 7,name => 'data-ththt'),[2] => array(id=> 66,name => 'data-kukuk'),[3] => array(id=> 85,name => 'data-gegegeg')
I want a result something like these array([0] => array(id=> 8,name => 'data-ryhryh'),
You see the point, id is filtered.
I will get the result through looping but if the main array is larger then it can consume time , I wonder if there is a short way than looping through all.
I would also want to know if php has something inbuilt for this one or anything close.
Advertisement
Answer
Create an associative array from $main_array
so you don’t have to loop to find the IDs.
$main_assoc = array_combine(array_column($main_array, 'id'), $main_array); $result = []; foreach ($filter_from_array_id as $id) { if (isset($main_assoc[$id])) { $result[] = $main_assoc[$id]; } }