PHP如何索引关联数组? [英] How does PHP index associative arrays?

查看:215
本文介绍了PHP如何索引关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在associative arrays中,如果未设置键,则会自动设置.但是在这种情况下似乎没有任何意义:

As I know, in associative arrays, if the keys is not set, it will be set automatically. But it seem doesn't make sense in this case:

$a = array( '1' => 'One', '3', '2' => 'Two');
print_r($a);

输出:

Array ( [1] => One [2] => Two )

那么"3"在哪里?

推荐答案

在用户定义的数组中,您正在手动分配键,表示数组的含义为

Within your user defined array you are assigning the keys manually your array means as

array(1 => 'One',3, 2 => 'Two');//[1] => One [2] => 3 [2] => Two

在这里,我们有两个相同的索引,并且按照 DOCS 提到最后一个覆盖第一个

Here we have two identical index and as per DOCS its mentioned that the last overwrite the first

语法索引=>值",以逗号分隔,定义索引和值. index的类型可以是字符串或整数.如果省略index,则会自动生成一个从0开始的整数索引.如果index是整数,则下一个生成的索引将是最大的整数索引+ 1.

Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1.

请注意,当定义了两个相同的索引时,最后一个将覆盖第一个.

为了过滤这种情况,您可以简单地进行如下更改

In order to filter this case you can simply make some changes as

array(1 => 'One',2 =>'Two',3) // array ([1] => One [2] => Two [3] => 3)
array(3,1 => 'One',2 =>'Two') //array ([0] => 3 [1] => One [2] => Two)
array(1 => 'One',2 => 3 ,3 =>'Two')// array([1] => One [2] => 3 [3] => Two)

DOCS检查参数

这篇关于PHP如何索引关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆