PHP获取一个索引和数组项

时间:2016-04-01 13:58:43

标签: php arrays random indexing

我有以下函数,它会随机询问数组的一个问题,并且必须将答案与要保存的问题的索引号一起发送到数据库,并在密码等事件上再次使用恢复等...

我的问题是我找不到用于同时获取索引编号和问题的方法或选项。

我已经尝试过密钥,search_array和其他方法,但无济于事。

请帮忙

由于

 <?php
    function secQ(){
        $questions = array();
        $questions[0] = "first question";
        $questions[1] = "second question";
        $questions[2] = "third question";
        $questions[3] = "fourth question";
        $questions[4] = "fifth qestion";
        $questions[5] = "sixth question";
        $rand_keys = array_rand($questions, 2);
    }
    ?>

3 个答案:

答案 0 :(得分:0)

您应该手动执行此操作。下面是一个通用函数,它应该适用于任何输入数组。

首先根据数组的大小生成一个随机数,然后返回与该数字对应的键和值。注意:我这样做是为了允许该方法使用关联数组。

function randomKeyValueFromArray($array) {
         $randomKey = rand(0,count($array));
         return [ array_keys($array)[$randomKey], array_values($array)[$randomKey] ];

}

使用方法:

$questions = array();
$questions[0] = "first question";
$questions[1] = "second question";
$questions[2] = "third question";
$questions[3] = "fourth question";
$questions[4] = "fifth qestion";
$questions[5] = "sixth question";

$randomQuestion = randomKeyValueFromArray($questions);

$questionKey = $randomQuestion[0];
$questionValue = $randomQuestion[1];

答案 1 :(得分:0)

这是一种将数组中的键和问题返回给调用者的方法。

<?php
function secQ(){
    $questions = array();
    $questions[0] = "first question";
    $questions[1] = "second question";
    $questions[2] = "third question";
    $questions[3] = "fourth question";
    $questions[4] = "fifth qestion";
    $questions[5] = "sixth question";

    $rand_key = array_rand($questions, 1);

    return array($rand_key, $questions[$rand_key]);
}

$q = secQ();
echo 'key is ' . $q[0];
echo 'question is ' . $q[1];
?>

答案 2 :(得分:0)

我找到了这个解决方案

<?php
function secQ()
{
    $questions = [
        "first question",
        "second question",
        "third question",
        "fourth question",
        "fifth qestion",
        "sixth question",
    ];

    $keys = array_keys($questions);

    $rand_keys = array_rand($keys, 2);

    $result = array();
    foreach ($rand_keys as $key) {
        $result[$key] = $questions[$key];
    }
    return $result;
}

var_dump(secQ());

第一个结果:

array(2) {
  [0]=> string(14) "first question"
  [1]=> string(15) "second question"
}

第二个结果:

array(2) {
  [4]=>string(13) "fifth qestion"
  [5]=>string(14) "sixth question"
}