연관 배열을 반복하고 키를 얻는 방법? [복제]
이 질문에는 이미 답변이 있습니다.
- PHP foreach 루프 키 값 4 답변
내 연관 배열 :
$arr = array(
1 => "Value1",
2 => "Value2",
10 => "Value10"
);
다음 코드를 사용하여 의 값으로 $v
채워짐$arr
foreach($arr as $v){
echo($v); // Value1, Value2, Value10
}
$arr
대신 키를 어떻게 얻 습니까?
foreach(.....){
echo($k); // 1, 2, 10
}
넌 할 수있어:
foreach ($arr as $key => $value) {
echo $key;
}
PHP 문서에 설명되어 있습니다.
를 사용 array_keys()
하면 PHP는 키로 채워진 배열을 제공합니다.
$keys = array_keys($arr);
foreach($keys as $key) {
echo($key);
}
또는 다음을 수행 할 수 있습니다.
foreach($arr as $key => $value) {
echo($key);
}
정기 for
루프로 답한 사람이 없습니까? 가끔은 더 읽기 찾아 선호 for
이상 foreach
그것이 그래서 여기 :
$array = array('key1' => 'value1', 'key2' => 'value2');
$keys = array_keys($array);
for($i=0; $i < count($keys); ++$i) {
echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}
/*
prints:
key1 value1
key2 value2
*/
foreach($array as $k => $v)
여기서 $ k는 키이고 $ v는 값입니다.
또는 키가 필요한 경우 array_keys ()
다음 루프를 사용하여 연관 배열에서 키와 값을 가져옵니다.
foreach ($array as $key => $value)
{
echo "<p>$key = $value</p>";
}
The following will allow you to get at both the key and value at the same time.
foreach ($arr as $key => $value)
{
echo($key);
}
While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)
$foo = array(
1 => "Value1",
2 => "Value2",
10 => "Value10"
);
while($bar = each($foo)){
echo $bar[0] . " => " . $bar[1];
}
I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.
Use $key => $val
to get the keys:
<?php
$arr = array(
1 => "Value1",
2 => "Value2",
10 => "Value10",
);
foreach ($arr as $key => $val) {
print "$key\n";
}
?>
<?php
$names = array("firstname"=>"maurice",
"lastname"=>"muteti",
"contact"=>"7844433339");
foreach ($names as $name => $value) {
echo $name." ".$value."</br>";
}
print_r($names);
?>
Oh I found it in the PHP manual.
foreach ($array as $key => $value){
statement
}
The current element's key will be assigned to the variable $key on each loop.
foreach($arr as $key=>$value){
echo($key); // key
}
If you use nested foreach()
function, outer array's keys print again and again till inner array values end.
<?php
$myArray = ['key_1' => ['value_1', 'value12'],
'key_2' => ['value_2', 'value22'],
'key_3' => ['value_3', 'value32']
];
$keysOfMyArray = array_key($myArray);
for ($x = 0; $x < count($myArray); $x++){
print "\t".$keysOfMyArray[$x]."\t\t".implode("\t\t",$myArray[$keysOfMyArray[$x]]."\n");
}
?>
참고URL : https://stackoverflow.com/questions/1951690/how-to-loop-through-an-associative-array-and-get-the-key
'Programming' 카테고리의 다른 글
스파크 콘솔에서 정보 메시지 표시를 중지하는 방법? (0) | 2020.06.02 |
---|---|
Ruby에서 문자열 또는 정수를 이진으로 변환하는 방법은 무엇입니까? (0) | 2020.06.02 |
Pandas 데이터 프레임에서 특이 값 탐지 및 제외 (0) | 2020.06.02 |
startActivity ()에서 번들을 전달 하시겠습니까? (0) | 2020.06.02 |
누군가가 최대 절전 모드에서 MappingBy를 설명 할 수 있습니까? (0) | 2020.06.02 |