菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
1238
1

分享几个有意思的数组方法

原创
05/13 14:22
阅读数 1778

使用传递的数组递归替换第一个数组的元素array_replace_recursive

$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);

分享几个有意思的数组方法

带索引检查计算数组的交集,用回调函数比较索引 array_intersect_uassoc

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");
print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));

分享几个有意思的数组方法

递归地合并一个或多个数组array_merge_recursive

$ar1 = array("color" => array("favorite" => "red"), 5);\
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));\
$result = array_merge_recursive($ar1, $ar2);

分享几个有意思的数组方法

使用传递的数组递归替换第一个数组的元素 array_replace_recursive

$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$basket = array_replace_recursive($base, $replacements);
print_r($basket);\

将一个线性数组转换为一个树,或者多维数组

    function array_stack (&$a, $p = '@parent', $c = '@children')
    {
      $l = $t = array();
      foreach ($a AS $key => $val):
        if (!$val[$p]) $t[$key] =& $l[$key];
        else $l[$val[$p]][$c][$key] =& $l[$key];
        $l[$key] = (array)$l[$key] + $val;
      endforeach;
      return $a = array('tree' => $t, 'leaf' => $l);
    }

    $node = array();
    $node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
    $node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
    $node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
    $node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
    $node[5] = array('@parent' => 4, 'title' => 'I am node 5.');
    print_r(array_stack($node));

发表评论

0/200
1238 点赞
1 评论
收藏
为你推荐 换一批