没有在循环中获取数组的实际值

时间:2016-08-31 22:56:08

标签: php arrays

请你看一下这个演示,让我知道为什么我只得到数组的索引号而不是实际值?

<?php

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);

foreach($rand_keys as $value) {
    print $value;
}


$length = count($rand_keys);
for ($i = 0; $i < $length; $i++) {
    print $rand_keys[$i];
}

?>

输出:

0202

1 个答案:

答案 0 :(得分:3)

现在你基本上这样做了:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2); //Array ( [0] => Random Key 1 [1] => Random Key 2 )

Foreach循环:

foreach($rand_keys as $value) {
  print $value;
}

╔═══════════════╦══════════════╗
║ Iteration Nr. ║    $value    ║
╠═══════════════╬══════════════╣
║ 1             ║ Random Key 1 ║
║ 2             ║ Random Key 2 ║
╚═══════════════╩══════════════╝

For loop:

$length = count($rand_keys);
for ($i = 0; $i < $length; $i++) {
  print $rand_keys[$i];
}

╔═══════════════╦════╦════════════════╦═════════╗
║ Iteration Nr. ║ $i ║ $rand_keys[$i] ║ $length ║
╠═══════════════╬════╬════════════════╬═════════╣
║ 1             ║ 0  ║ Random Key 1   ║ 2       ║
║ 2             ║ 1  ║ Random Key 2   ║ 2       ║
╚═══════════════╩════╩════════════════╩═════════╝

所以array_rand()只返回随机密钥。使用返回的键访问输入数组中的元素:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);

foreach($rand_keys as $key) {
    echo $input[$key];
}