在给定条件下使用另一个数组从数组中获取值的快速方法

Quick way to get the value from array with another array giving condiition

假设有一个 array $filter_from_array_id = array(2,8,52,45,7)

然后还有一个数组

$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')

我想要这样的结果array([0] => array(id=> 8,name => 'data-ryhryh'),

看到重点了,id被过滤了

我会通过循环得到结果,但是如果主数组更大,那么它会消耗时间,我想知道是否有比循环所有的更短的方法。

我还想知道 php 是否内置了这个或任何类似的东西。

$main_array 创建关联数组,这样您就不必循环查找 ID。

$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];
    }
}

有一个函数:array_filter and in_array 检查数组中的值。

array_filter(array $array [, callable $callback [, int $flag = 0 ]]) : array

迭代数组中的每个值,将它们传递给回调函数。 如果回调函数 returns TRUE,则数组的当前值为 返回结果数组。数组键被保留。

你不需要任何循环来做这样的操作。 PHP array functions.

编辑:由于变量可见性重写了代码。

更正并测试了括号 array() == [ ] 的 PHP7:phptester

// Declaring $filters ... is not visible in function
// and can't be pass as arguments to the callback.
function filters () {
 return [2,3,52,45,7];
};

// The array to filter
$main_array = [['id' => 8,'name' => 'data-ryhryh'], ['id'=> 7,'name' => 'data-ththt']];

// Filter data having an id in the array of filters.
// Adding & to improve memory usage
$result = array_filter($main_array, function (array &$item) {
  return in_array($item['id'], filters());
});

print_r($result);
// result = Array([1] => Array([id] => 7 [name] => data-ththt))

注意:$main_arraykeys会被保留