如何向现有数组添加额外值

时间:2017-05-01 07:10:47

标签: php arrays

如何向现有数组添加额外值

$item   = get_post_meta($post->ID, 'extra_fileds', true); 

当我打印$ item时,我得到以下内容

Array 
(
  [0] => Array ( [name] => test1 [type] => this1 [location] => 1 ) 
  [1] => Array ( [name] => test2 [type] => this2 [location] => 2 )
)

我想添加一个额外的字段并使其像`

Array 
( 
[0] => Array ( [name] => test1 [type] => this1 [location] => 1 ) 
[1] => Array ( [name] => test2 [type] => this2 [location] => 2 ) 
[2] => Array ( [name] => test3 [type] => this3 [location] => 3 )
)

提前谢谢

4 个答案:

答案 0 :(得分:1)

$item[] = ['name'=>'test3','type'=>'this3','location'=>3];

答案 1 :(得分:1)

您可以使用array_push$rows[]来解决您的问题。

Try this code snippet here     

ini_set('display_errors', 1);

$rows=Array ( 
    0 => Array ( "name" => "test1","type" => "this1", "location" => 1 ),
    1 => Array ( "name" => "test2" ,"type" => "this2", "location" => 2 ) );

$arrayToAdd=Array ( "name" => "test3","type" => "this3", "location" => 3 );

解决方案1:

array_push($rows, $arrayToAdd);

解决方案2:

$rows[]=$arrayToAdd;

答案 2 :(得分:0)

使用array push

$new_array_item=array("name" => "test3","type" => "this3", "location" => 3);
array_push($item, $new_array_item);
print_r($item);

答案 3 :(得分:0)

您的数组目前存储在$ item中。

要添加新项目,请使用以下括号:[]。

这是你的代码:

$item[] = [
    'name' => 'test3'
    'type' => 'this3'
    'location' => 3
]

您可以根据需要随意添加更多项目。

我认为这是最好的解决方案,但你也可以看一下php array_push()函数。

相关问题