php method to add key-value pairs to an array: First create a PHP sample file; then use the foreach statement to add key-value pairs to the array, with statements such as "foreach ($a as &$item) { $item['b'] = "value";}".
Recommended: "PHP Video Tutorial"
Use foreach to add key-value pairs to the array in php
In PHP, the frequency of using foreach to traverse arrays is very high, and its performance is higher than the combination of list() and each() to traverse arrays:
When traversing the first level of a two-digit array array, and want to add a new key-value pair to the second array. For example, I have a two-dimensional array structure like this
$a = array( array( 'a' => "first" ), array( 'a' => "second" ) );
This is my plan to add a key-value pair to each array in the second layer
'b' => "value"
If foreach is used at this time
foreach ($a as $item) { $item['b'] = "value"; }
The result obtained is the same as the original array, and the key-value pair 'b' is not added => "value"
only We need to make some modifications to the above code to achieve our needs, that is, add an address character & before $item, as follows
foreach ($a as &$item) { $item['b'] = "value"; }
The array obtained in this way is the content we want .
The above is the detailed content of php adds key-value pairs to array. For more information, please follow other related articles on the PHP Chinese website!