转自:http://www.phpstudy.net/php/165.html

PHP array_fill 用给定的值填充数组

array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill — 用给定的值填充数组

说明

array array_fill ( int $start_index , int $num , mixed $value )

array_fill() 用 value 参数的值将一个数组填充 num 个条目,键名由 start_index 参数指定的开始。注意 num 必须是一个大于零的数值,否则 PHP 会发出一条警告。

Example #1 array_fill() 例子

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

$a 现在是:

Array
(
[5] => banana
[6] => banana
[7] => banana
[8] => banana
[9] => banana
[10] => banana
)

参见 str_repeat() 和 range()

 

PHP array_fill note #1

To better handle the problem of sparse array completion mentioned a couple years ago...

What you really need in this scenario is an empty array containing all the desired keys, and a sparse array containing the keys and values you want overridden. This PHP5 function does that. (The PEAR package PHP_Compat should be able to fill in the gap -- array_combine() --  for a 4.3 install, if necessary.)

<?php
    function array_complete(
        $keys="",                // array of keys you need filled, in order
        $sparse=""                // sparse array to override blanks
    )
    {
        if(!is_array($sparse)) 
            $sparse=array();
    
        if(!is_array($keys))
            return $sparse;
    
        return array_merge(        
            array_combine(        // create an associative array
                $keys,            // your list of keys
                array_fill(        // blank value for each key
                    0,count(
                        $keys
                    ),""
                )
            ),$sparse            // merge with your incomplete array
        );
    }
?>

This merges in your sparse array (inserting any additional keys in that array after the ones you've specified), placing its values in the key order you specify, leaving all the other values blank.

Test call: var_dump(array_complete(array("test1", "test2", "test3", "test4", "test5"), array("test3" => "test3", "test1" => "test1", "garbage" => "garbage")));

Result: array(6) {
  ["test1"]=>
  string(5) "test1"
  ["test2"]=>
  string(0) ""
  ["test3"]=>
  string(5) "test3"
  ["test4"]=>
  string(0) ""
  ["test5"]=>
  string(0) ""
  ["garbage"]=>
  string(7) "garbage"
}

PHP array_fill note #2

This is what I recently did to quickly create a two dimensional array (10x10), initialized to 0:

<?php
  $a = array_fill(0, 10, array_fill(0, 10, 0));
?>

This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.

PHP array_fill note #3

For PHP < 4.2.0 users:

Add this to your script:
if (!function_exists('array_fill')) {
   require_once('array_fill.func.php');
}

and the array_fill.func.php file:

<?php

// For PHP version < 4.2.0 missing the array_fill function,
// I provide here an alternative. -Philippe

function array_fill($iStart, $iLen, $vValue) {
    $aResult = array();
    for ($iCount = $iStart; $iCount < $iLen + $iStart; $iCount++) {
        $aResult[$iCount] = $vValue;
    }
    return $aResult;
}

?>

PHP array_fill note #4

array_fill() cannot be used to setup only missing keys in an array. This  may be necessary for example before using implode()  on a sparse filled array. 
The solution is to use this function:

<?php 
function array_setkeys(&$array, $fill = NULL) { 
  $indexmax = -1; 
  for (end($array); $key = key($array); prev($array)) { 
    if ($key > $indexmax) 
      $indexmax = $key; 
  } 
  for ($i = 0; $i <= $indexmax; $i++) { 
    if (!isset($array[$i])) 
      $array[$i] = $fill; 
  } 
  ksort($array); 

?>

This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.

array_fill 用给定的值填充数组的更多相关文章

  1. 任务型对话(一)—— NLU(意识识别和槽值填充)

    1,概述 任务型对话系统越来越多的被应用到实际的场景中,例如siri,阿里小密这类的产品.通常任务型对话系统都是基于pipline的方式实现的,具体的流程图如下: 整个pipline由五个模块组成:语 ...

  2. jsoncpp封装和解析字符串、数字、布尔值和数组

    使用jsoncpp进行字符串.数字.布尔值和数组的封装与解析. 1)下载jsoncpp的代码库 百度网盘地址 :http://pan.baidu.com/s/1ntqQhIT 2)解压缩文件 json ...

  3. Array.splice返回值是数组

    import flash.display.MovieClip; import flash.display.DisplayObject; var m:MovieClip = new MovieClip( ...

  4. PHP按值合并数组

    /** * PHP按值合并数组 * */ function my_array_merge(&$array1, &$array2) { $result = Array(); foreac ...

  5. javascript 常见数组操作( 1、数组整体元素修改 2、 数组筛选 3、jquery 元素转数组 4、获取两个数组中相同部分或者不同部分 5、数组去重并倒序排序 6、数组排序 7、数组截取slice 8、数组插入、删除splice(需明确位置) 9、数组遍历 10、jQuery根据元素值删除数组元素的方)

    主要内容: 1.数组整体元素修改 2. 数组筛选 3.jquery 元素转数组 4.获取两个数组中相同部分或者不同部分 5.数组去重并倒序排序 6.数组排序 7.数组截取slice 8.数组插入.删除 ...

  6. 把一个给定的值存储到一个整数中指定的几个位《C与指针5.8.5》

    编写一个函数,把一个给定的值存储到一个整数中指定的几个位.它的原型如下: int store_bit_field(int original_value, int value_to_store, uns ...

  7. 根据Bool值挑选数组中元素

    根据Bool值挑选数组中元素 觉得有用的话,欢迎一起讨论相互学习~Follow Me 使用Boolean类型的数组挑选一维数组中的值 使用一维Boolean数组选取数组中的特定元素,对应位置为True ...

  8. params.row[params.column.key] vue h函数 当前单元格 h函数 div 属性 值或数组 render

    params.row[params.column.key] vue h函数 当前单元格 h函数 div 属性 值或数组 render

  9. js javascript 如何获取某个值在数组中的下标

    js 某个值在数组中的下标javascript中知道一个数组中的一个元素的值,如何获取数组下标JS 获取数组某个元素下标 函数方法 采用prototype原型实现方式,查找元素在数组中的索引值js查找 ...

随机推荐

  1. BZOJ 2648: SJY摆棋子

    2648: SJY摆棋子 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 2968  Solved: 1011[Submit][Status][Disc ...

  2. 【BZOJ-4353】Play with tree 树链剖分

    4353: Play with tree Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 31  Solved: 19[Submit][Status][ ...

  3. 【BZOJ-3910】火车 倍增LCA + 并查集

    3910: 火车 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 262  Solved: 90[Submit][Status][Discuss] De ...

  4. linux中/和/root(~) 和 /home

    winodws是森林型目录结构,它有很多根,如C.D.E.F等都是它的根目录,然后在其实创建子目录linux是树型目录结构,它只有一个根就是/目录,然后在/目录在有子目录如/root./home./e ...

  5. xudyh的gcd模板

    hdu 5019 #include <cstdlib> #include <cctype> #include <cstring> #include <cstd ...

  6. Discuz! X2.5 /source/class/helper/helper_seo.php Remote Code Execution Vul

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 SEO模块中的preg_replace+修正符e+双引号引发的远程代码执 ...

  7. 企业应用系统设计分享PPT

    因今天上午需要为团队做一个分享,所以昨晚连夜写了一个<企业应用系统设计>的PPT,因为时间比较短,写的比较急.现在把PPT贴出来,做一个记录.同时也希望对大家有用. 文件我上传到了百度网盘 ...

  8. ARPSpoofing教程(三) - 捕获数据包

    1: #include"pcap.h" 2: //每次捕获到数据包时,libpcap都会自动调用这个回调函数 3: void packet_handler(u_char *para ...

  9. zabbix 3.0快速安装简介(centos 6)

    zabbix快速安装 系统版本:centos 6 1.yum源配置和zabbix.msyql安装 rpm -ivh http://mirrors.aliyun.com/zabbix/zabbix/3. ...

  10. MyEclipse快捷键大全(绝对全)

    存盘 Ctrl+s(肯定知道) 注释代码 Ctrl+/ 取消注释 Ctrl+\(Eclipse3已经都合并到Ctrl+/了) 代码辅助 Alt+/ 快速修复 Ctrl+1 代码格式化 Ctrl+Shi ...