转自: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-2440】完全平方数 容斥原理 + 线性筛莫比乌斯反演函数 + 二分判定

    2440: [中山市选2011]完全平方数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 2371  Solved: 1143[Submit][Sta ...

  2. 【bzoj1178】 Apio2009—CONVENTION会议中心

    http://www.lydsy.com/JudgeOnline/problem.php?id=1178 (题目链接) 题意 给出n个区间,问在区间两两不相交的情况下最多能选出多少区间,并输出字典序最 ...

  3. Androidstudio 的svn配置 需要忽略的目录

  4. mysql 某周的起始和结束日期

    转自:http://bbs.csdn.net/topics/370096126 t_table有数据如下:year    Week2011    22011    32011    42011     ...

  5. JPA事务总结

    http://www.soso.io/article/65405.html 事务管理是JPA中另一项重要的内容,了解了JPA中的事务管理,能够进一步掌握JPA的使用.事务管理是对一系列操作的管理,它最 ...

  6. ubuntu下的ssh

    ubuntu默认是没有安装openssh-server的,今天简单的写一下ubuntu上ssh的安装与使用. 一.服务器端 安装 apt-get install openssh-server #安装 ...

  7. OpenGLES入门笔记一

    学习地址:http://www.raywenderlich.com/3664/opengl-tutorial-for-ios-opengl-es-2-0 中文翻译:http://www.cnblogs ...

  8. centos7 + VMware Workstation Pro

    centos7 + VMware Workstation Pro安装 centos 7 镜像文件 下载地址https://www.centos.org/download/ 笔者是使用的DVD ISO, ...

  9. JS-结合html综合练习js的对象——班级成绩表制作

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>对 ...

  10. SVN cleanup操作反复失败解决办法

    今天在更新项目的时候遇到一个问题,按惯例要cleanup才能重新更新.但是很不幸,在cleanup的时候又遇到了问题! 1    svn cleanup failed–previous operati ...