如何使用键位置访问关联数组?

时间:2022-09-26 08:21:18

Let's say I have this code:

假设我有这个代码:

    $games = [
    "Boys" => ["Danny", "Ben"],
    "Girls" => ["Ashley", "Sandra"]
];

And for example, I want to access Danny's name. I can access it by using

例如,我想访问Danny的名字。我可以通过使用来访问它

$games["Boys"][0]

But what if I want to access it by it's bit index (for future foreach loops)? I tried something like:

但是如果我想通过它的位索引(对于未来的foreach循环)来访问它呢?我试过类似的东西:

 $games[0][0]

But I get an error (unindexed something).

但我得到一个错误(没有索引的东西)。

1 个解决方案

#1


1  

Use array_values to create a numerical array from $games, then index that:

使用array_values从$ games创建一个数值数组,然后索引:

echo array_values($games)[0][0];

Hope that helps

希望有所帮助

#1


1  

Use array_values to create a numerical array from $games, then index that:

使用array_values从$ games创建一个数值数组,然后索引:

echo array_values($games)[0][0];

Hope that helps

希望有所帮助