【问题标题】:Check if array has 10 elements if not create blank elements如果不创建空白元素,则检查数组是否有 10 个元素
【发布时间】:2017-07-21 16:47:06
【问题描述】:

数组需要 10 个元素(对于存储过程,需要 10 个值)。

用户可以提交少于 10 个。在这种情况下,数组应该自动为剩余的任何内容创建空白元素。

这个变量最初是通过这样的帖子来的:

<?php
  $containers = $_POST['cntnum']; // could be equal or less than 10, no more
  $count = count($containers);
  $remainder = 10 - $count;

  // trying to loop and set remaining elements to ''
  for($i = 0; $i < $remainder; $i++)
  {
    // this where I'm lost
  }
?>

这是我将变量发送到存储过程时的样子:

 $sans = 'value1', 'value2', 'value3', '', '', '', '', '', '', '';

我正在尝试使用 for 循环将剩余的数组元素设置为 ''。

也许我不需要 for 循环。也许还有另一种方式。我愿意接受建议。

我怎样才能做到这一点?

注意:我正在尝试在这里完成我之前的问题:stored procedure that accepts multiple parameters

【问题讨论】:

  • 在你的循环中做 $containers[] = ""; 这将把下一个数组值设置为空白。
  • @GrumpyCrouton - 显示您的代码有效。有人在下面提供了相同的答案。如果您创建一个,我会将您的标记为已回答。

标签: php arrays stored-procedures


【解决方案1】:

一个通用的答案,给定一个小于 10 个值的数组 $values,并且您不想保留键/索引,您可以使用 array_fill() 创建一个填充有占位符值的特定大小的数组,以及使用array_replace() 将其与您的$values“合并”;例如:

<?php

$values = ['foo', 'bar', 'baz'];
$merged = array_replace(array_fill(0, 10, ''), $values);

print_r($merged);

产量:

Array
(
    [0] => foo
    [1] => bar
    [2] => baz
    [3] => 
    [4] => 
    [5] => 
    [6] => 
    [7] => 
    [8] => 
    [9] => 
)

参考

希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    您只需为数组键设置一个空值。

    $containers = $_POST['cntnum']; // could be equal or less than 10, no more
    $count      = count($containers);
    $remainder  = 10 - $count;
    // trying to loop and set remaining elements to ''
    for ($i = 0; $i < $remainder; $i++) {
        //if you don't specify a key, it uses the next available key.
        $containers[] = "";
    }
    

    或者,如果您想摆脱循环,请使用array_pad

    使用 array_pad:

    $containers = array_pad($containers, 10, '');
    

    【讨论】:

    • 谢谢您,先生。这正是我想要的。
    • @JohnBeasley 没问题^.^。很高兴我能帮上忙!
    【解决方案3】:

    您可以使用array_fill() 用空字符串填充剩余的索引。

    【讨论】:

      【解决方案4】:

      您可以像这样向数组中添加一个新的“空白”项:

      $containers[] = '';
      

      所以如果你把它放到你的for循环中,它会在数组中添加指定数量的空白项。

      【讨论】:

        【解决方案5】:

        这正是 array_pad 的设计目的:

        <?php
        
        $sans = ['value1', 'value2', 'value3'];
        $padded = array_pad($sans, 10, '');
        
        print_r($padded);
        

        =

        Array
        (
            [0] => value1
            [1] => value2
            [2] => value3
            [3] => 
            [4] => 
            [5] => 
            [6] => 
            [7] => 
            [8] => 
            [9] => 
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-21
          • 2013-07-20
          • 1970-01-01
          • 2018-03-03
          相关资源
          最近更新 更多