dpt1712 2014-06-03 08:24
浏览 87
已采纳

随机插入数据库

I want to insert a huge list of contacts in my database (for some performance tests).

I have some troubles with randomizing some data.

   $input = array("city1", "city2", "city3");
   $city= shuffle($input);

If I understood clear the shuffle function, I need to pass it an array and will just suffle it, right? Then what is wrong here?

PS. I know, just basic PHP stuffs, but I couldn't find any similar example with arrays here on stackoverflow, so please don't get angry for opening this topic.

  • 写回答

1条回答 默认 最新

  • dsbx40787736 2014-06-03 08:27
    关注

    Your bit of code: $city=shuffle($input); doesn't pass the shuffled array to the $city variable - but rather the function return which is TRUE or FALSE depending on whether it completed successfully. The function actually shuffles your ORIGINAL array.

    You are assigning the Boolean (true or false) to your $city array - which is the output of the function - ie, did it work.

    <?php
       $input = array("city1", "city2", "city3");
    
        print_r($input);
    
        shuffle($input);
    
        print_r($input);
    ?>
    

    The Shuffle function shuffles the original array.

    Output:

    Array
    (
        [0] => city1
        [1] => city2
        [2] => city3
    )
    Array
    (
        [0] => city1
        [1] => city3
        [2] => city2
    )
    

    Edit: Answering comment:

    You access the individual elements of the array using the standard PHP format of square brackets and a key?

    <?php
        $input = array("city1", "city2", "city3");
        // Access one element of the array:
        echo $input[0];
    
        // shuffle the array about.
        shuffle($input);
    
        // Access the same element of the array 
        // and see if the data is the same
        echo $input[1];
    ?>
    

    The output of this is a string with any of the bits of the array, then the same element - which may or may not have the same output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法