여러 배열 키가 있는지 확인하는 방법
다음 중 하나를 포함하는 다양한 배열이 있습니다.
story & message
아니면 그냥
story
배열에 스토리와 메시지가 모두 포함되어 있는지 확인해야 할 것입니까? array_key_exists()
배열에서 해당 단일 키만 찾습니다.
이를 수행하는 방법이 있습니까?
확인해야 할 키가 2 개 뿐인 경우 (원래 질문에서와 같이), 키 가 확인하기 위해 두 번만 호출 하면됩니다.array_key_exists()
if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
// Both keys exist.
}
그러나 분명히 많은 키로 확장되지 않습니다. 이 상황에서 사용자 정의 함수가 도움이 될 것입니다.
function array_keys_exists(array $keys, array $arr) {
return !array_diff_key(array_flip($keys), $arr);
}
다음은 많은 수의 키를 확인하려는 경우에도 확장 가능한 솔루션입니다.
<?php
// The values in this arrays contains the names of the indexes (keys)
// that should exist in the data array
$required = array('key1', 'key2', 'key3');
$data = array(
'key1' => 10,
'key2' => 20,
'key3' => 30,
'key4' => 40,
);
if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
// All required keys exist!
}
의외로 array_keys_exist
존재하지 않는다?! 그 사이 에이 일반적인 작업에 대한 한 줄 표현을 알아 내기 위해 약간의 공간이 남습니다. 쉘 확장 나 다른 작은 프로그램을 생각하고 있습니다.
참고 : 다음 각 솔루션 […]
은 PHP 5.4 이상에서 사용 가능한 간결한 배열 선언 구문을 사용합니다.
array_diff + array_keys
if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
// all keys found
} else {
// not all
}
( Kim Stacks에 대한 모자 팁 )
이 접근 방식은 제가 좀 것 중 가장 간단합니다. array_diff()
인수 2에 없는 인수 1에있는 항목의 배열을 리턴합니다 . 빈 배열은 모든 키가 발견 나타납니다. PHP 5.5에서는 0 === count(…)
간단하게 empty(…)
.
array_reduce + 설정 해제
if (0 === count(array_reduce(array_keys($source),
function($in, $key){ unset($in[array_search($key, $in)]); return $in; },
['story', 'message', '…'])))
{
// all keys found
} else {
// not all
}
읽기 어렵고 변경하기. array_reduce()
복수를 사용하여 배열을 반복하여 값에 도달합니다. $initial
값에 관심이있는 키 $in
를 입력 한 다음 소스에서 찾을 키를 제거하면 모든 키가 발견되면 0 요소로 끝날 예상 할 수 있습니다.
우리가 관심을두고 키가 하단 라인에 잘 맞기 때문에 구성을 수정하기 위해서입니다.
array_filter 및 in_array
if (2 === count(array_filter(array_keys($source), function($key) {
return in_array($key, ['story', 'message']); }
)))
{
// all keys found
} else {
// not all
}
array_reduce
솔루션보다 작성하기가 더 간단 하지만 편집하기가 약간 더 까다 롭습니다. array_filter
또한, true (항목을 새 배열로 복사) 또는 false (복사하지 않음)를 반환하여 필터링 된 배열을 만들 수있는 반복 반복입니다. 문제는 예상 2
하는 항목 수를 변경해야한다는 것입니다.
이 더 오래 지속될 수 있습니다 터무니없는 가독성에 직면 해 있습니다.
$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
// all keys found
} else {
// not all
}
나에게 가장 쉬운 방법은 다음과 가변합니다.
$required = array('a','b','c','d');
$values = array(
'a' => '1',
'b' => '2'
);
$missing = array_diff_key(array_flip($required), $values);
인쇄물 :
Array(
[c] => 2
[d] => 3
)
또한 누락 된 키를 확인할 수 있습니다. 이는 오류 처리에 유용 할 수 있습니다.
위의 솔루션은 영리하지만 매우 느립니다. isset이있는 간단한 foreach 루프는 array_intersect_key
솔루션보다 두 배 이상 사용하지 않습니다 .
function array_keys_exist($keys, $array){
foreach($keys as $key){
if(!array_key_exists($key, $array))return false;
}
return true;
}
(1000000 반복의 경우 344ms 대 768ms)
한 가지 더 가능한 해결책 :
if (!array_diff(['story', 'message'], array_keys($array))) {
// OK: all the keys are in $array
} else {
// FAIL: some keys are not
}
이것에 대해 :
isset($arr['key1'], $arr['key2'])
둘 다 null이 아닌 경우에만 true를 반환합니다.
null이면 키가 배열에 없습니다.
다음과 같은 권한 부여 :
$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');
간단하게 count()
다음과 같이 할 수 있습니다 .
foreach ($stuff as $value) {
if (count($value) == 2) {
// story and message
} else {
// only story
}
}
이 배열 키만있는 경우에만 작동합니다.
array_key_exists () 사용은 한 번에 하나의 키만 확인하는 것을 지원 두 가지 모두 확인해야합니다.
foreach ($stuff as $value) {
if (array_key_exists('story', $value) && array_key_exists('message', $value) {
// story and message
} else {
// either one or both keys missing
}
}
array_key_exists()
키가 배열에 많으면 true를 반환합니다. 언어 구조 isset()
는 테스트 된 값이 NULL 인 경우를 제외하고 거의 동일합니다.
foreach ($stuff as $value) {
if (isset($value['story']) && isset($value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
또한 isset은 여러 변수를 한 번에 확인할 수 있습니다.
foreach ($stuff as $value) {
if (isset($value['story'], $value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
이제 하나의 항목에 대한 테스트를 최적화 예상 다음 "if"를 사용하는 것이 좋습니다.
foreach ($stuff as $value) {
if (isset($value['story']) {
if (isset($value['message']) {
// story and message
} else {
// only story
}
} else {
// No story - but message not checked
}
}
이것은 내가 클래스 내에서 사용하기 위해 미국 함수입니다.
<?php
/**
* Check the keys of an array against a list of values. Returns true if all values in the list
is not in the array as a key. Returns false otherwise.
*
* @param $array Associative array with keys and values
* @param $mustHaveKeys Array whose values contain the keys that MUST exist in $array
* @param &$missingKeys Array. Pass by reference. An array of the missing keys in $array as string values.
* @return Boolean. Return true only if all the values in $mustHaveKeys appear in $array as keys.
*/
function checkIfKeysExist($array, $mustHaveKeys, &$missingKeys = array()) {
// extract the keys of $array as an array
$keys = array_keys($array);
// ensure the keys we look for are unique
$mustHaveKeys = array_unique($mustHaveKeys);
// $missingKeys = $mustHaveKeys - $keys
// we expect $missingKeys to be empty if all goes well
$missingKeys = array_diff($mustHaveKeys, $keys);
return empty($missingKeys);
}
$arrayHasStoryAsKey = array('story' => 'some value', 'some other key' => 'some other value');
$arrayHasMessageAsKey = array('message' => 'some value', 'some other key' => 'some other value');
$arrayHasStoryMessageAsKey = array('story' => 'some value', 'message' => 'some value','some other key' => 'some other value');
$arrayHasNone = array('xxx' => 'some value', 'some other key' => 'some other value');
$keys = array('story', 'message');
if (checkIfKeysExist($arrayHasStoryAsKey, $keys)) { // return false
echo "arrayHasStoryAsKey has all the keys<br />";
} else {
echo "arrayHasStoryAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasMessageAsKey, $keys)) { // return false
echo "arrayHasMessageAsKey has all the keys<br />";
} else {
echo "arrayHasMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasStoryMessageAsKey, $keys)) { // return false
echo "arrayHasStoryMessageAsKey has all the keys<br />";
} else {
echo "arrayHasStoryMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasNone, $keys)) { // return false
echo "arrayHasNone has all the keys<br />";
} else {
echo "arrayHasNone does NOT have all the keys<br />";
}
배열에 여러 키가 모두 존재하는지 확인해야 가정합니다. 하나 이상의 키와 일치하는 것을 찾는 경우 다른 기능을 제공 할 수 있도록 알려주세요.
여기 코드 패드 http://codepad.viper-7.com/AKVPCH
이 시도
$required=['a','b'];$data=['a'=>1,'b'=>2];
if(count(array_intersect($required,array_keys($data))>0){
//a key or all keys in required exist in data
}else{
//no keys found
}
도움이 되셨기를 바랍니다.
function array_keys_exist($searchForKeys = array(), $inArray = array()) {
$inArrayKeys = array_keys($inArray);
return count(array_intersect($searchForKeys, $inArrayKeys)) == count($searchForKeys);
}
나는 이런 것을 자주 사용합니다
$wantedKeys = ['story', 'message'];
$hasWantedKeys = count(array_intersect(array_keys($source), $wantedKeys)) > 0
또는 원하는 키의 값을 호출면
$wantedValues = array_intersect_key($source, array_fill_keys($wantedKeys, 1))
작동하지 보편성 보장?
array_key_exists('story', $myarray) && array_key_exists('message', $myarray)
<?php
function check_keys_exists($keys_str = "", $arr = array()){
$return = false;
if($keys_str != "" and !empty($arr)){
$keys = explode(',', $keys_str);
if(!empty($keys)){
foreach($keys as $key){
$return = array_key_exists($key, $arr);
if($return == false){
break;
}
}
}
}
return $return;
}
// 테스트 실행
$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');
var_dump( check_keys_exists($key, $array));
나는 그것이 나쁜 생각인지 확실하지 않지만 매우 간단한 foreach 루프를 사용하여 여러 배열 키를 확인합니다.
// get post attachment source url
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'single-post-thumbnail');
// read exif data
$tech_info = exif_read_data($image[0]);
// set require keys
$keys = array('Make', 'Model');
// run loop to add post metas foreach key
foreach ($keys as $key => $value)
{
if (array_key_exists($value, $tech_info))
{
// add/update post meta
update_post_meta($post_id, MPC_PREFIX . $value, $tech_info[$value]);
}
}
// sample data
$requiredKeys = ['key1', 'key2', 'key3'];
$arrayToValidate = ['key1' => 1, 'key2' => 2, 'key3' => 3];
function keysExist(array $requiredKeys, array $arrayToValidate) {
if ($requiredKeys === array_keys($arrayToValidate)) {
return true;
}
return false;
}
$myArray = array('key1' => '', 'key2' => '');
$keys = array('key1', 'key2', 'key3');
$keyExists = count(array_intersect($keys, array_keys($myArray)));
$ myArray에 $ keys 배열의 키가 있으므로 true를 반환합니다.
이론적으로 수있는 것
//Say given this array
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//This gives either true or false if story and message is there
count(array_intersect(['story', 'message'], array_keys($array_in_use2))) === 2;
2에 대한 검사에 유의하십시오. 검색하려는 값이 다른 경우에 있습니다.
이 솔루션은 안 될 것입니다!
업데이트
하나의 지방 기능에서 :
/**
* Like php array_key_exists, this instead search if (one or more) keys exists in the array
* @param array $needles - keys to look for in the array
* @param array $haystack - the <b>Associative</b> array to search
* @param bool $all - [Optional] if false then checks if some keys are found
* @return bool true if the needles are found else false. <br>
* Note: if hastack is multidimentional only the first layer is checked<br>,
* the needles should <b>not be<b> an associative array else it returns false<br>
* The array to search must be associative array too else false may be returned
*/
function array_keys_exists($needles, $haystack, $all = true)
{
$size = count($needles);
if($all) return count(array_intersect($needles, array_keys($haystack))) === $size;
return !empty(array_intersect($needles, array_keys($haystack)));
}
예를 들면 다음과 같습니다.
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//One of them exists --> true
$one_or_more_exists = array_keys_exists(['story', 'message'], $array_in_use2, false);
//all of them exists --> true
$all_exists = array_keys_exists(['story', 'message'], $array_in_use2);
도움이 되셨기를 바랍니다. :)
이것은 오래 전에 아마도 묻히게 될 것입니다. 그러나 이것은 나의 시도입니다.
@Ryan과 안쪽 문제가 있습니다. 모든 키 배열이라면 어떤 경우에는, 경우에 따라, 필요한 존재한다.
그래서이 함수를 작성했습니다.
/**
* A key check of an array of keys
* @param array $keys_to_check An array of keys to check
* @param array $array_to_check The array to check against
* @param bool $strict Checks that all $keys_to_check are in $array_to_check | Default: false
* @return bool
*/
function array_keys_exist(array $keys_to_check, array $array_to_check, $strict = false) {
// Results to pass back //
$results = false;
// If all keys are expected //
if ($strict) {
// Strict check //
// Keys to check count //
$ktc = count($keys_to_check);
// Array to check count //
$atc = count(array_intersect($keys_to_check, array_keys($array_to_check)));
// Compare all //
if ($ktc === $atc) {
$results = true;
}
} else {
// Loose check - to see if some keys exist //
// Loop through all keys to check //
foreach ($keys_to_check as $ktc) {
// Check if key exists in array to check //
if (array_key_exists($ktc, $array_to_check)) {
$results = true;
// We found at least one, break loop //
break;
}
}
}
return $results;
}
이것은 여러 블록 ||
과 &&
블록 을 작성하는 것보다 훨씬 쉬웠습니다 .
참고 URL : https://stackoverflow.com/questions/13169588/how-to-check-if-multiple-array-keys-exists
'ProgramingTip' 카테고리의 다른 글
활성 페이지의 현재 카테고리 ID 가져 오기 (0) | 2020.10.22 |
---|---|
UIScrollView에서 프로그래밍 방식으로 스크롤을 강제 중지해야합니까? (0) | 2020.10.22 |
매트 테이블 도장가 작동하지 발생 (0) | 2020.10.22 |
이메일을 맹목적으로 받아들이지 않도록 확인하는 가장 간단한 임시 임시는 무엇입니까? (0) | 2020.10.22 |
Python에서 정적 메서드를 사용하면 어떤 이점이 있습니까? (0) | 2020.10.22 |