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

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

问题描述

据我所知,在关联数组中,如果未设置键,则会自动设置.但在这种情况下似乎没有意义:

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 =>values",以逗号分隔,定义索引和值.索引可以是字符串或整数类型.省略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)

文档检查参数

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

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