php数组操作的常用方法

在 PHP 中,有三种类型的数组:

  • 数值数组 – 带有数字 ID 键的数组
  • 关联数组 – 带有指定的键的数组,每个键关联一个值
  • 多维数组 – 包含一个或多个数组的数组

看具体实例:

创建数组

<?php
    //方式 1
    $cars = array("Volvo","BMW","Toyota");
    //方式 2
    $cars[0] = "Volvo";
    $cars[1] = "BMW";
    $cars[2] = "Toyota";
    //方式 3
    $cars = [
      "Volvo",
      "BMW",
      "Toyota",
    ]
?>

<?php
    $cars = array("Volvo","BMW","Toyota");
    echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

获取数组的长度 – count () 函数

<?php
   $cars = array("Volvo","BMW","Toyota");
    echo count($cars);
?>

遍历数组

<?php
    $cars = array("Volvo","BMW","Toyota");
  //第一种方式
    $arrlength = count($cars);
    for($x = 0 ;$x < $arrlength ;$x++) {
        echo $cars[$x];
        echo "<br>";
    }
    //第二种方式
    foreach ($cars as $key => $value){
        echo $value;
        echo "<br/>";
    }
?>

array_chunk () 函数 (把数组分割为带有两个元素的数组块)

<?php
    $cars = array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
    print_r(array_chunk($cars,2));
?>

array_keys () 函数 (返回包含数组中所有键名的一个新数组)

<?php
    $a = array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
    print_r(array_keys($a));
?>

array_push () 函数 (向数组尾部插入 “blue” 和 “yellow”)

<?php
    $a = array("red","green");
    array_push($a,"blue","yellow");
    print_r($a);
?>

array_pop () 函数 (删除数组中的最后一个元素)

<?php
    $a = array("red","green","blue");
    array_pop($a);
    print_r($a);
?>

array_reverse () 函数 (返回翻转顺序的数组)

<?php
    $a = array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
    print_r(array_reverse($a));
?>

sort () 函数 (对数组中的元素按字母进行升序排序)

<?php
    $cars = array("Volvo","BMW","Toyota");
    sort($cars);
?>