Random current article function-PHP array_rand () function

Source: Internet
Author: User

During development, a page is refreshed and the article function is randomly obtained. The array_rand () function in the PHP function is used. array_rand (array, number) has two parameters, the array parameter indicates that you want to obtain an array. The number parameter is optional. The second parameter is used to determine the elements to be selected. The default value is 1 .. If more than one element is selected, an array containing the random key name is returned. Otherwise, the key name of the element is returned. (Remember: understand the meaning of bold), the returned is an array key name, not the corresponding value in the array. When I first started using it, I thought it was a direct return value, old values cannot be obtained. The specific usage is as follows:
PHP code

  1. ........
  2. .......
  3. While ($ res = mysql_fetch_object ($ rsql ))
  4. {
  5. $ Arr [$ I] [id] = $ res-> art_id;
  6. $ Arr [$ I] [url] = siteurl. "art-php-". "$ res-> art_id" ..html;
  7. $ Arr [$ I] [title] = $ res-> art_title;
  8. $ I;
  9. }
  10. $ Arr1 = array_rand ($ arr, 10 );
  11. $ Arr2 = array ();
  12. Foreach ($ arr1 as $ key => $ value)
  13. {
  14. $ Arr2 [$ key] [id] = $ arr [$ value] [id];
  15. $ Arr2 [$ key] [url] = $ arr [$ value] [url];
  16. $ Arr2 [$ key] [title] = $ arr [$ value] [title];
  17. }
  18. Return $ arr2;

The code I wrote is as follows:
$ Arr indicates the array that I have obtained. $ arr1 returns 10 random array key names, and then reassembles the array with the return key through foreach.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.