dqqxkq4047
2016-08-31 22:56 阅读 36
已采纳

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

Can you please take a look at this demo and let me know why I am getting only the index number of array instead of actual value?

<?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];
}

?>

Output:

0202
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongtong848825 dongtong848825 2016-08-31 22:58

    Right now you basically do this:

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

    Foreach loop:

    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       ║
    ╚═══════════════╩════╩════════════════╩═════════╝
    

    So array_rand() just returns random keys. Use that returned keys to access elements in your input array:

    $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
    $rand_keys = array_rand($input, 2);
    
    foreach($rand_keys as $key) {
        echo $input[$key];
    }
    
    点赞 5 评论 复制链接分享

相关推荐