zoukankan      html  css  js  c++  java
  • 5种PHP创建数组的方式

    在PHP以及其他程序语言程序设计中,经常会用到数组的创建,在前端开发中,js的数组创建可以由[]和new Array()直接创建和赋值。然而PHP创建数组的方法有哪些呢?在查阅资料并且网上收集整理总结了下:

    1. 使用array创建数组,是最常见和便捷的一个方式 :
     
    $arr = array('a','b','c');
    $arr[] = 'a' ; $arr[] = 'b' ; $arr[] = 'c';
    $arr = array('name' => '关羽' , 'age' => 23 , 'sex' => '男');
    

      

    2. 有时候需要创建一个长度为len的一个随机数组,所以就可以用range():
     
       定义:array range(first,second,step)  //first:元素最小值   second:元素最大值  step:元素步长(要增加的量)
    $number = range(0,5); 
    print_r ($number); 
     
    //打印:Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) 
     
    $number = range(0,50,10); 
    print_r ($number); 
     
    //打印:Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 ) 
     
    $letter = range("a","d"); 
    print_r ($letter); 
     
    //打印:Array ( [0] => a [1] => b [2] => c [3] => d ) 
    

      3.当然,在某些特定需求下,需要把某些变量存入数组,这些变量的变量名转换成键名,变量值转换成键值(前提:该变量存在):

    $firstname = "Peter"; 
    $lastname = "Griffin"; 
    $age = "38"; 
    $result = compact("firstname", "lastname", "age"); 
    print_r($result); 
     
    //打印: Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 ) 
     
    $firstname = "Peter"; 
    $lastname = "Griffin"; 
    $age = "38"; 
    $name = array("firstname", "lastname"); 
    $result = compact($name, "location", "age"); 
    print_r($result); 
     
    //打印:Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 ) 
    //由于$location变量不存在,所以存入不了数组
    

      

    4. 将两个数组合并为一个新的数组,第一个数组的值是新数组的键名,第二个数组里面的值是新数组的键值:
     
    定义:array_combine()函数可以将两个数组合并成一个新数组,其中的一个数组是键名,另一个数组的值为键值。 
    $a1=array("a","b","c","d"); 
    $a2=array("Cat","Dog","Horse","Cow"); 
    print_r(array_combine($a1,$a2)); 
     
    //打印:Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow ) 
    

      

    5. 创建键值一样具有固定长度的数组:
     
    定义:array_fill(start,number,value)  //start:起始索引 number:值的个数 value:数组值
    $a=array_fill(2,3,"Dog"); 
    print_r($a); 
     
    //打印:Array ( [2] => Dog [3] => Dog [4] => Dog ) 
    

      

  • 相关阅读:
    Arpa's weak amphitheater and Mehrdad's valuable Hoses
    Arpa's loud Owf and Mehrdad's evil plan
    穷游中国在统题
    2016 ACM Amman Collegiate Programming Contest D Rectangles
    区间求和
    Redis 连接池的问题
    eBay 使用ReviseInventoryStatusCall调整库存和价格
    eBay Notification介绍
    Quartz.Net 配置模板范例
    Quartz.net misfire实践
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/9407721.html
Copyright © 2011-2022 走看看