dsnhalq37505 2017-04-07 00:44
浏览 18
已采纳

使用数组:使用简单条件从数组中提取数组

I have an array:

$quizzes = array();
            $Quiz = array(
                'quiz_id'   => $quiz_id,
                'correct'   => $correctAnswers
            );
            $quizzes[] = $Quiz;

$quizzes is an array which contains many quizzes called Quiz, which in turn have $Quiz['quiz_id'] and $Quiz['correct']. Now what I'm trying to do is to select a particular quiz from the list of quizzes in $quizzes where quiz_id=1.

If such quiz exists, I would like to echo quiz is found. If no $Quiz with such id exists, echo no quiz is found.

A simple solution that I came up with is to do a foreach loop.

foreach($quizzes as $Quiz) if($Quiz['quiz_id'] == 1) {} else {}

However, since I have more than 1 quiz, it returns the else statement as many times as there are $Quiz['quiz_id'] != 1 which is many many times.

  • 写回答

2条回答 默认 最新

  • doubihuai8468 2017-04-07 00:51
    关注

    Indexing your array such as $quizzes[ $quiz_id ] = $Quiz; would permit you to go straight to that item in the array.

    So take your existing line of

    $quizzes[] = $Quiz;
    

    and change it to

    $quizzes[ $quiz_id ] = $Quiz;
    

    then you can use

    if( isset( $quizzes[ $quiz_id ] ) )
    {
      echo 'found the quiz!';
    }
    else
    {
      echo 'no quiz found';
    }
    

    where $quiz_id is the id of the quiz you wish to locate

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

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号