搜索数组:array_filter vs循环 [英] Search Array : array_filter vs loop

查看:96
本文介绍了搜索数组:array_filter vs循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是PHP新手,需要有关数组搜索的建议。

I am really new in PHP and need a suggestion about array search.

如果我想在多维数组中搜索元素,可以使用 array_filter 或我可以遍历数组,看看是否存在与我的条件匹配的元素。

If I want to search for an element inside a multidimensional array, I can either use array_filter or I can loop through the array and see if an element matching my criteria is present.

我看到两个建议在很多地方。哪个更快?下面是一个示例数组。

I see both suggestion at many places. Which is faster? Below is a sample array.

Array ( 
  [0] => Array ( 
    [id] => 4e288306a74848.46724799
    [question] => Which city is capital of New York?
    [answers] => Array ( 
      [0] => Array ( 
        [id] => 4e288b637072c6.27436568 
        [answer] => New York 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 0 
      ) 
      [1] => Array ( 
        [id] => 4e288b63709a24.35955656 
        [answer] => Albany 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 1 
      ) 
    )
  )
)

我正在这样搜索。

$thisQuestion = array_filter($pollQuestions, function($q) {
  return questionId == $q["id"];
});


推荐答案

Array_Filter


迭代将输入数组中的每个值传递给
回调函数。如果回调函数返回true,则来自输入的当前
值将返回到结果数组中。数组键保留

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

与我相同。

这篇关于搜索数组:array_filter vs循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆