在php的数组元素中添加更多的键值


add more key values in the elements of array in php

假设有一个数组它的第一个元素是

Array ( [name] => gaurav pandey [education] => MCA )

现在我想插入更多的属性所以最终的结果应该是:

Array ( [name] => gaurav pandey [education] => MCA [occupation] => developer [passion] => programming)

如何在php中实现?我已经看到实例及其属性的动态创建,但仍然不能弄清楚如何实现它在php数组

我很确定你只是在问如何插入一个新的键/值到数组中,这是一个难以置信的基本的PHP语法问题。

请参阅手册,详细说明使用方括号语法创建/修改:

要更改某个值,使用该元素的键为该元素赋一个新值。要删除键/值对,请调用它的unset()函数。

 <?php
 $arr = array(5 => 1, 12 => 2);
 $arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script
 $arr["x"] = 42; // This adds a new element to
                // the array with key "x"
 unset($arr[5]); // This removes the element from the array
 unset($arr);    // This deletes the whole array
 ?>

为数组添加属性的语法:

$a = array (
    "name" => "gaurav pandey",
    "education" => "MCA"
);
$a["occupation"] = "developer";
$a["passion"] = "programming"

你应该先阅读PHP的数组手册。检查这个例子:

// create the associative array:
$array = array(
    'name' => 'gaurav pandey'
);
// add elements to it
$array ['education'] = 'MCA';
$array ['occupation'] = 'Developer';

除了@meagar的帖子,我还建议您看看PHP手册中的array_functions页面:

http://php.net/manual/en/ref.array.php

例如,组合数组、遍历数组、排序数组等。

也可以合并数组

<?php
$array1 = array("name" => "gaurav pandey","education" => "MCA");
$array2 = array("color" => "green", "shape" => "trapezoid", "occupation" => "developer", "passion" => "programming");
$result = array_merge($array1, $array2);
print_r($result);
?>

您也可以使用array_push()。如果您要一次向数组中添加多个项目,但会增加一些开销,那么这很方便。