php 不常用但实用函数

1.trim

rtrim() 从字符串右侧移除字符:
ltrim() - 移除字符串左侧的空白字符或其他预定义字符
trim() - 移除字符串两侧的空白字符或其他预定义字符

<?php
$str = "Hello World!";
echo $str . "<br>"; //Hello World!
echo rtrim($str,"World!"); // Hello
?>

2.sprintf

把百分号(%)符号替换成一个作为参数进行传递的变量:

<?php
$number = 2;
$str = "Shanghai";
$txt = sprintf("There are %u million cars in %s.",$number,$str);
echo $txt;
?>
//There are 2 million cars in Shanghai.

3.array_slice

从数组的第三个元素开始取出,并返回数组中的其余元素:

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
//Array ( [0] => blue [1] => yellow [2] => brown )

4.array_shift

删除数组中的第一个元素(red),并返回被删除元素的值:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a);//red
print_r ($a);//Array ( [b] => green [c] => blue )
?>

5.array_unshift

在数组头部加入元素

<?php
$a=array("a"=>"red","b"=>"green");
array_unshift($a,"blue");
print_r($a);
?>
//Array ( [0] => blue [a] => red [b] => green )

6.array_walk

<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
?>
//结果
The key a has the value red
The key b has the value green
The key c has the value blue

if ($goodsList) {
    array_walk($goodsList, function ($goods) use (&$goodsListArr) {
        $giftId = get_property($goods, 'giftId');
        $giftSpecId = get_property($goods, 'giftSpecId');
        $gift = GiftLogic::getInstance()->getDetail($giftId);
        $giftSpec = GiftLogic::getInstance()->getGiftSpecDetail($giftSpecId);
   
        $goodsListArr[] = [
            'idCode' => IdCodeUtil::encode(get_property($goods, 'id')),
            'giftName' => get_property($gift, 'name'),
        ];
    });

    $goodsNums = array_sum(array_column($goodsList, 'totalNums'));
    $sellNums = array_sum(array_column($goodsList, 'sellNums'));
}
unset($goodsList);

7.array_column

获取数组某一列的值

<?php
// 表示由数据库返回的可能记录集的数组
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Bill',
    'last_name' => 'Gates',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Steve',
    'last_name' => 'Jobs',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Mark',
    'last_name' => 'Zuckerberg',
  )
);

$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

8.array_sum

返回数组中所有值的和(5+15+25):

<?php
$a=array(5,15,25);
echo array_sum($a);
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值