简体   繁体   中英

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() .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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