我有一个数组,我想存储一次,它永远不需要更改。 我想具有不同的功能来检索此信息。我尝试使用类,但是PHP不允许您将数组和值存储为可以使用的属性。这是一个简单的任务,要么我丢失了某些东西,要么PHP无法完成我想象中的简单任务。
<?php
$questions = array();
$questions[0]['question'] = "How many legs does a spider have?";
$questions[0]['correct_answer'] = "8";
$questions[0]['answer'][0] = "8";
$questions[0]['answer'][1] = "7";
$questions[0]['answer'][2] = "6";
$questions[0]['answer'][3] = "5";
$questions[0]['answer'][4] = "4";
$questions[0]['answer'][5] = "3";
$questions[0]['answer'][6] = "2";
$questions[0]['answer'][7] = "1";
$questions[0]['answer'][8] = "0";
//Questions number 2
$questions[1]['question'] = "What do you put in a Hamburger bun?";
$questions[1]['correct_answer'] = "Hamburger";
$questions[1]['answer'][0] = "Lemons";
$questions[1]['answer'][1] = "Dog food";
$questions[1]['answer'][2] = "Pancakes";
$questions[1]['answer'][3] = "Hamburger";
$questions[1]['answer'][4] = "Flies";
$questions[1]['answer'][5] = "Mormons";
$questions[1]['answer'][6] = "H.P Lovecraft";
$questions[1]['answer'][7] = "A Space Man";
$questions[1]['answer'][8] = "Soup";
//Questions number 3
$questions[2]['question'] = "What is Obama's first name?";
$questions[2]['correct_answer'] = "Barack";
$questions[2]['answer'][0] = "Ludwig";
$questions[2]['answer'][1] = "Homer";
$questions[2]['answer'][2] = "Icarus";
$questions[2]['answer'][3] = "Mcenzie";
$questions[2]['answer'][4] = "Barack";
$questions[2]['answer'][5] = "David";
$questions[2]['answer'][6] = "Donald";
$questions[2]['answer'][7] = "Stewart";
$questions[2]['answer'][8] = "Lewis";
//Questions number 4
$questions[3]['question'] = "How long is a netflix trial?";
$questions[3]['correct_answer'] = "One Month";
$questions[3]['answer'][0] = "Eighteen Days";
$questions[3]['answer'][1] = "Two Weeks";
$questions[3]['answer'][2] = "One Year";
$questions[3]['answer'][3] = "Six Months";
$questions[3]['answer'][4] = "One Month";
$questions[3]['answer'][5] = "Ninty Days";
$questions[3]['answer'][6] = "One Day";
$questions[3]['answer'][7] = "12 Years";
$questions[3]['answer'][8] = "3 Lunar months";
function get_question_by_id($id){
return $questions[$id];
}
?>
question_by_id应该为问题提供正确的答案以及$ questions [$ id]的所有可能答案。
答案 0 :(得分:0)
在访问它们之前,您需要先从全局范围中获取$ questions。将功能更改为
function get_question_by_id($id){
global $questions;
return $questions[$id];
}
或
function get_question_by_id($id, $questions){
return $questions[$id];
}
// You then have to call it like this:
$question = get_question_by_id($id, $questions);
答案 1 :(得分:0)
我刚刚在一个单独的函数中声明了它,并称为get_questions,我可以调用in_array函数来搜索返回值。将其发布为答案,我将关闭它,Getters和Setters :) KISS方法