如何在PHP中访问数组的第N个元素 [英] How to access N-th element of an array in PHP

查看:321
本文介绍了如何在PHP中访问数组的第N个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很尴尬地问这个问题,很可能是重复的,但是我的Google搜索结果很短(我猜搜索不正确),这样的基本问题使我很生气.

I'm embarrassed to ask this and it's most likely a duplicate, but my google results are coming up short (im searching incorrectly I guess) and such a basic question is infuriating me.

我有一个数组,其中包含我不知道的值.

I have an array containing values I don't know.

在Java中,要查看第二个条目,我将使用类似

In java, to have a look at the 2nd entry, I would use something like

var = array[1]

我了解Php数组是键值对,但是我怎样才能简单地查看数组中的第n个值以查看它的键值对,甚至更好,然后仅访问键/值?

I understand Php arrays are key-value pairs, but how can I simply look at the nth value in an array to see it's key-value pair, and even better, then access just the key / value?

推荐答案

如果您的密钥是数字的,则其工作原理完全相同:

If your keys are numeric, then it works exactly the same:

$arr = ['one', 'two', 'three']; // equivalent to [0 => 'one', 1 => 'two', 2 => 'three']
echo $arr[1]; // two

如果您的键不是数字键或不是连续数字键,则将变得有些棘手:

If your keys are not numeric or not continuously numeric, it gets a bit trickier:

$arr = ['one', 'foo' => 'bar', 42 => 'baz'];

如果您知道,则需要:

echo $arr['foo']; // bar

但是,如果您只知道偏移量,则可以尝试以下操作:

However, if you only know the offset, you could try this:

$keys = array_keys($arr);
echo $arr[$keys[1]];

或以数字方式为数组重新索引:

Or numerically reindex the array:

$values = array_values($arr);
echo $values[1];

或切片:

echo current(array_slice($arr, 1, 1));

尽管如此,您很可能还是想遍历整个数组,这通常是对未知内容数组进行的操作.如果内容未知,那么您仍然对某个特定的偏移量感兴趣似乎很奇怪.

Most likely you want to be looping through the array anyway though, that's typically what you do with arrays of unknown content. If the content is unknown, then it seems odd that you're interested in one particular offset anyway.

foreach ($arr as $key => $value) {
    echo "$key: $value", PHP_EOL;
}

这篇关于如何在PHP中访问数组的第N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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