PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법
Oct 17, 2024 pm 05:20 PMRetrieve Array Keys During Foreach Loop: PHP
When working with arrays in PHP, it's often necessary to retrieve both the keys and values within a foreach loop. The key() function provides a convenient way to access the current key during the iteration. However, in certain scenarios, it may not yield the desired result.
Consider the following code that aims to generate an HTML table from the sample array:
<code class="php">foreach($samplearr as $item){ print "<tr\><td>" . key($item) . "</td>\><td>" . $samplearr['value1'] . "</td>\><td>" . $samplearr['value2'] . "</td>\></tr\>"; }</code>
This code incorrectly returns the key as "value1" instead of the actual key of the outer array (e.g., 4722).
To resolve this issue, it's necessary to use the array key as the iteration variable:
<code class="php">foreach($samplearr as $key => $item){ print "<tr\><td>" . $key . "</td>\><td>" . $item['value1'] . "</td>\><td>" . $item['value2'] . "</td>\></tr\>"; }</code>
By declaring the loop variable as "$key," you can directly access the key of the outer array within the loop. This code will now correctly generate the expected HTML table:
<code class="html"><tr\><td>4722</td>\><td>52</td>\><td>46</td>\></tr\> <tr\><td>4922</td>\><td>22</td>\><td>47</td>\></tr\> <tr\><td>7522</td>\><td>47</td>\><td>85</td>\></tr\></code>
위 내용은 PHP의 Foreach 루프 내에서 배열 키를 검색하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Laravel Back End : Part 2, React가있는 React 앱 구축

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법
