English 中文(简体)
编制(索引)
原标题:Creating (Inserting) an array index
  • 时间:2012-05-01 08:14:24
  •  标签:
  • php
  • arrays

我的发言如下。

[0]
{
    [0]=> a 
    [2]=> b 
    [5]=> c 
    [6]=> d 
}

我不想插入未经加固的阵列指数,将其数值定为0。

e.g:在这种情况下,希望产出像以下,而不是以上。 任何人都可以向我展示一部法律样本。 i 试图使用阵列——填充,但只是在尾插入阵列指数。

array_fill($b1, 1, "0");

希望产出:

[0]
    {
        [0]=> a 
        [1]=> 0 
        [2]=> b 
        [3]=> 0 
        [4]=> 0 
        [5]=> c 
        [6]=> d 
    }
最佳回答

通过您的阵列,监测钥匙。 以往的任何一次,从目前的钥匙中分离出1个以上,但只剩下一段短暂的时间才能赶上阵列内容。

$newArray = array();
$lastKey = 0;

foreach ( $array as $key => $value ) {
  while ( $lastKey++ < $key ) $newArray[] = 0;
  $newArray[$key] = $value;
}

产出如下:

Array
(
    [0] => a
    [1] => 0
    [2] => b
    [3] => 0
    [4] => 0
    [5] => c
    [6] => d
)

Demo:

问题回答

我认为(没有测试)这项工作将:

  // get the first used key
  list($firstkey, $firstval)=each(asort($input_array));
  $input_array[$firstkey]=$firstval;

  // get the last used key
  list($lastkey, $lastval)=each(arsort($input_array));
  $input_array[$lastkey]=$lastval;

  $output_array=array_replace(array_fill($firstkey, $lastkey, 0), $input_array);




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...