PHP数组

### 数组
在PHP中,我们需要用到array()进行数组的创建:

array();

PHP中的数组总共有三种类型:

  • 数值数组:带有数字ID键的数组
  • 关联数组:带有指定的键的数组,每个键关联一个值
  • 多维数组:包含一个或多个数组的数组
$fruit = array("apple", "pear", "orange");
count()获取数组的长度

Example:

echo "数组的长度是:".count($fruit);

OutPut:

数组的长度是:3
遍历数组

在这里使用for循环进行遍历,也可以使用其他方式对数组进行遍历。

for ($x = 0; $x < $fruitArrLength; $x++){
    echo $fruit[$x];
    echo "=====";
}
关联数组

关联数组是使用我们自己为数组分配键而不是从0到数组的总个数减一。

// 方式一:
$fruit=array("001"=>"apple", "003"=>"orange", "002"=>"pear");
// 方式二:
$fruit["001"]="apple";
$fruit["002"]="orange";
$fruit["003"]="pear";

遍历关联数组

foreach ($fruit1 as $x=>$x_value){
    // $x 为对应的key   $x_value 为对应的value(类似OC中的字典)
}
数组排序
  • sort(): 对数组升序排序
  • rsort():对数组降序排序
  • asort():根据关联数组的值,对数组升序排序
  • arsort():根据关联数组的值,对数组降序排序
  • ksort():根据关联数组的键,对数组升序排序
  • krsort():根据关联数组的键,对数组降序排序

Example:

// 其中sort()和rsort(),默认只对非关联数组进行排序,如果对关联数组进行排序的话,其结果会覆盖之前的键,也就是说不管之前的键如何设定,排序之后的键都会从排序后的第一个元素开始,键从0到数组中元素的个数减一。

// sort():
sort($fruit);
echo "对数组进行升序排序:";
for ($x = 0; $x < count($fruit); $x++){
    echo $fruit[$x];
    echo "-->";
}

// rsort():
rsort($fruit);
echo "对数组进行降序排序:";
for ($x = 0; $x < count($fruit); $x++){
    echo $fruit[$x];
    echo "-->";
}

// asort():
asort($fruit1);
echo "根据关联数组的值,对数组升序排序:";
foreach ($fruit1 as $x=>$x_value){
    echo "Key=" . $x.", Value = " . $x_value;
    echo ";     ";
}

// arsort():
arsort($fruit1);
echo "根据关联数组的值,对数组降序排序:";
foreach ($fruit1 as $x=>$x_value){
    echo "Key=" . $x.", Value = " . $x_value;
    echo ";     ";
}

// ksort()
ksort($fruit1);
echo "根据关联数组的键,对数组降序排序:";
foreach ($fruit1 as $x=>$x_value){
    echo "Key=" . $x.", Value = " . $x_value;
    echo ";     ";
}

// krsort()
krsort($fruit1);
echo "根据关联数组的键,对数组降序排序:";
foreach ($fruit1 as $x=>$x_value){
    echo "Key=" . $x.", Value = " . $x_value;
    echo ";     ";
}

OutPut:

对数组进行升序排序:apple-->orange-->pear-->
对数组进行降序排序:pear-->orange-->apple-->
根据关联数组的值,对数组升序排序:Key=001, Value = apple;     Key=003, Value = orange;     Key=002, Value = pear;
根据关联数组的值,对数组降序排序:Key=002, Value = pear;     Key=003, Value = orange;     Key=001, Value = apple;
根据关联数组的键,对数组降序排序:Key=001, Value = apple;     Key=002, Value = pear;     Key=003, Value = orange; 
根据关联数组的键,对数组降序排序:Key=003, Value = orange;     Key=002, Value = pear;     Key=001, Value = apple;     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值