dowaw80220 2011-07-22 14:26
浏览 34
已采纳

搜索数组:array_filter vs loop

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

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

I am searching like this.

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

4条回答 默认 最新

  • dqqxkq4047 2011-07-22 14:28
    关注

    Array_Filter

    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.

    as for me same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿