Cara Mengambil Kekunci Tatasusunan dalam PHP Foreach Loop dengan betul

Linda Hamilton
Lepaskan: 2024-10-17 17:19:02
asal
605 orang telah melayarinya

How to Correctly Retrieve Array Keys in PHP Foreach Loop

Retrieving Array Keys in a Foreach Loop: Addressing an Error in Key Retrieval

In PHP, iterating over an array's values using a foreach loop can sometimes lead to unexpected behavior when accessing the keys. This is especially true if the array contains nested data structures.

Understanding the Error

Consider the following code:

<code class="php">foreach ($sampleArray as $item) {
    echo "&lt;tr&gt;&lt;td&gt;" . key($item) . "&lt;/td&gt;&lt;td&gt;" . $sampleArray['value1'] . "&lt;/td&gt;&lt;td&gt;" . $sampleArray['value2'] . "&lt;/td&gt;&lt;/tr&gt;";
}</code>
Salin selepas log masuk

As illustrated in the provided question, this code will only output the key of the nested array (e.g., "value1"), not the desired key of the outer array itself (e.g., "4722").

Correcting the Issue

To retrieve the outer array key correctly, we need to modify the code slightly:

<code class="php">foreach ($sampleArray as $key => $item) {
    echo "&lt;tr&gt;&lt;td&gt;" . $key . "&lt;/td&gt;&lt;td&gt;" . $item['value1'] . "&lt;/td&gt;&lt;td&gt;" . $item['value2'] . "&lt;/td&gt;&lt;/tr&gt;";
}</code>
Salin selepas log masuk

By adding a $key variable to the foreach loop, we can access the actual key of the outer array. This will then correctly print the desired key in the table.

Atas ialah kandungan terperinci Cara Mengambil Kekunci Tatasusunan dalam PHP Foreach Loop dengan betul. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!