In PHP, to add a column after an array, we can use the array_push() function or direct assignment.
Let’s introduce these two methods below.
Method 1: Use array_push() function
array_push() function can add one or more elements to the end of the array. We can use this function to add a column after the array.
The specific implementation method is as follows:
<?php // 定义一个数组 $oldArr = array( array('name'=>'Tom', 'age'=>20, 'gender'=>'male'), array('name'=>'Lucy', 'age'=>21, 'gender'=>'female'), array('name'=>'Jack', 'age'=>22, 'gender'=>'male') ); // 定义需要增加的一列数据 $new = 'address'; // 遍历数组,将新数据添加到数组中 foreach($oldArr as &$value) { $value[$new] = ''; } // 输出结果 print_r($oldArr); ?>
Output result:
Array ( [0] => Array ( [name] => Tom [age] => 20 [gender] => male [address] => ) [1] => Array ( [name] => Lucy [age] => 21 [gender] => female [address] => ) [2] => Array ( [name] => Jack [age] => 22 [gender] => male [address] => ) )
From the output result, we can see that we successfully added a column after the array.
Method 2: Direct assignment
Using direct assignment, you can also add a column after the array.
The implementation method is as follows:
<?php // 定义一个数组 $oldArr = array( array('name'=>'Tom', 'age'=>20, 'gender'=>'male'), array('name'=>'Lucy', 'age'=>21, 'gender'=>'female'), array('name'=>'Jack', 'age'=>22, 'gender'=>'male') ); // 遍历数组,为每个元素赋值 foreach($oldArr as &$value) { $value['address'] = ''; } // 输出结果 print_r($oldArr); ?>
The output result is also:
Array ( [0] => Array ( [name] => Tom [age] => 20 [gender] => male [address] => ) [1] => Array ( [name] => Lucy [age] => 21 [gender] => female [address] => ) [2] => Array ( [name] => Jack [age] => 22 [gender] => male [address] => ) )
Through the above two methods, we can add a column after the PHP array and implement the array Data integrity and compliance controls.
The above is the detailed content of php adds a column after the array. For more information, please follow other related articles on the PHP Chinese website!