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 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];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?