简体   繁体   English

在循环中使用键值对递增php数组

[英]Increment php array with key value pairs in a loop

How do I increment(add more values) to an array with key value pairs in a loop. 如何在循环中将具有键值对的数组增加(添加更多值)。

$field['choices'] = array(
   'custom' => 'My Custom Choice'
 );

Let's says I want to add three more choices from another array? 假设我要从另一个阵列中再添加三个选择?

Output I want to achieve: 我要实现的输出:

$field['choices'] = array(
  'custom1' => 'My Custom Choice1'
  'custom2' => 'My Custom Choice2'
  'custom3' => 'My Custom Choice3'
  'custom4' => 'My Custom Choice4'
);

Iterate, and concatenate the index to the prefix in your key: 迭代索引并将其连接到键中的前缀:

for ($i = 2; $i <= 4; $i++) {
    $field['choices']['custom' . $i] = 'My Custom Choice' . $i;
}

You can use the array functions to sort or merge. 您可以使用数组函数进行排序或合并。

Or you can do something like this: 或者,您可以执行以下操作:

$field['choices']['custom'] = 'My Custom Choice';
$field['choices']['custom2'] = 'My Custom Choice';
$field['choices']['custom3'] = 'My Custom Choice';
$field['choices']['custom4'] = 'My Custom Choice';

You would want to use array_merge() . 您可能要使用array_merge()

From the manual: 从手册中:

 array array_merge ( array $array1 [, array $... ] ) 

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. 将一个或多个数组的元素合并在一起,以便将一个数组的值附加到上一个数组的末尾。 It returns the resulting array. 它返回结果数组。

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. 如果输入数组具有相同的字符串键,则该键的后一个值将覆盖前一个。 If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. 但是,如果数组包含数字键,则后面的值将不会覆盖原始值,而是将其附加。

As you had outlined in your question: 正如您在问题中概述的那样:

$field['choices'] = array(
   'custom' => 'My Custom Choice'
 );

So: 所以:

$array = $field['choices'];

to simplify the following example: 简化以下示例:

$otherArray = range(1, 3); // another array with 3 values

$array += $otherArray; // adding those three values (with _different_ keys)

done. 完成。 The + operator with arrays is called union. 带数组的+运算符称为联合。 You find it documented here: 您可以在此处找到文档:

So as long as the other array you want to add has three different keys compared to the one array you add it to, you can use the + operator. 因此,与要添加的另一个数组相比,只要要添加的另一个数组具有三个不同的键,就可以使用+运算符。

Here is the code i would use to add $otherArray values to a custom increment array key value 这是我将$otherArray值添加到自定义增量数组键值的代码

if (count($field['choices']) === 1) {
    $field['choices']['custom1'] = $field['choices']['custom'];
    unset($field['choices']['custom'];
    $i = 2;
} else {
    $i = count($field['choices']) + 1;
}//END IF
foreach ($otherArray as $key => $val) {
    $field['choices']['custom' . $i] =  $val;//Where val is the value from the other array
    $i++;
}//END FOREACH LOOP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM