Heim  >  Artikel  >  Backend-Entwicklung  >  php 数组添加关联元素的方法小结_PHP教程

php 数组添加关联元素的方法小结_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:43:551104Durchsuche

我们这里介绍的是在数组中再增加关联数组了,这个就合成了多维数组,下面我来给大家举几个实例,希望对各位同学会有所帮助哈。

在"php 数组添加元素方法总结这篇文章中介绍了如何给数组添加元素,那么我想添加$array=array('title'=>'php教程')这样的元素怎么办呢。

array_push, array_pop, array_shift, array_unshift 这几个函数都是为数字类型的索引数组设计的。
要想实现关联数组的添加可以使用array_merge方法或者是+操作符

我们先来看数组中增加数组元素

1. php中增加数组元素的方法:

(1)通过赋值增加数组元素 :$states[‘name’]=’Tom’;

(2)int array_push(array target_array,mixed variable [,mixed variable…]) 函数将variable增加到target_array的末尾,成功时返回true,否则返回false,其中variable可以是多个。

(3)int array_unshift(array target_array,mixed variable [,mixed variable…]) 函数将variable增加到target_array的数组头,成功时返回true,否则返回false,其中variable可以是多个。所有已有的数值键都会相应地修改,而关联键不受影响。

(4)array array_pad(array target_array,integer length,mixed pad_value) 将target_array 的大小增加到length指定的长度。

使用array_push或者array_unshift这两个方法行么?

答案是否定的


具体方法:

1.使用array_merge方法实现类似array_unshift在开头添加元素的功能

 代码如下 复制代码

$queue = array('a', 'B');
$queue = array_merge(array('front' => 'hello'), $queue);
/*
Array
(
    [front] => hello
    [0] => a
    [1] => b
)
*/
?>

2.+操作符

 代码如下 复制代码

$queue = array('a', 'B');
$queue = array('front' => 'Hello') + $queue;
?>

输出结果与使用array_merge方法一样。

3.在元素结尾添加关联数组元素

 代码如下 复制代码

$queue = array('a', 'B');
$queue['front'] = 'hello';
/*
输出
Array
(
    [0] => a
    [1] => b
    [front] => hello 
)
*/
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/633139.htmlTechArticle我们这里介绍的是在数组中再增加关联数组了,这个就合成了多维数组,下面我来给大家举几个实例,希望对各位同学会有所帮助哈。 在...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn