programing

PHP : 배열에서 키 가져 오기?

copysource 2021. 1. 16. 20:41
반응형

PHP : 배열에서 키 가져 오기?


나는 이것이 PHP에서 매우 쉽고 내장 된 기능이라고 확신하지만 아직 보지 못했습니다.

지금 제가하고있는 일은 다음과 같습니다.

foreach($array as $key => $value) {
    echo $key; // Would output "subkey" in the example array
    print_r($value);
}

대신 다음과 같은 작업을 수행하여 모든 foreach 루프에서 "$ key => $ value"를 작성하지 않도록 할 수 있습니까? (의사 코드)

foreach($array as $subarray) {
    echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
    print_r($value);
}

감사!

어레이 :

Array
(
    [subKey] => Array
        (
            [value] => myvalue
        )

)

key () 사용할 수 있습니다 .

<?php
$array = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4
);

while($element = current($array)) {
    echo key($array)."\n";
    next($array);
}
?>

array_search기능을 사용하십시오 .

php.net의 예

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;

$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}


$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));


foreach질문에서 설명한대로 루프 인 경우 사용하는 $key => $value것이 빠르고 효율적입니다.


foreach루프 에 있고 싶다면 foreach($array as $key => $value)확실히 권장되는 접근 방식입니다. 언어에서 제공하는 간단한 구문을 활용하십시오.


Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)


Try this

foreach(array_keys($array) as $nmkey)
    {
        echo $nmkey;
    }

Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!

PHP Manual: array_search() (similiar to .indexOf() in other languages)

public function getKey(string $value, array $target)
{
    $key = array_search($value, $target);

    if ($key === null) {
        throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
    }

    if ($key === false) {
        throw new DomainException("The search value does not exists in the target array.");
    }

    return $key;
}

ReferenceURL : https://stackoverflow.com/questions/3317856/php-get-key-from-array

반응형