PHP에서는 배열에 대한 작업이 매우 자주 발생합니다. 배열은 여러 관련 값을 저장할 수 있는 순서가 지정되지 않은 데이터 구조입니다. 배열에 요소가 존재하는지 확인해야 할 경우 PHP의 in_array 함수를 사용하여 확인할 수 있습니다. 그러나 배열의 특정 속성에 요소가 존재하는지 확인해야 하는 경우 이를 어떻게 달성할 수 있습니까?
function isExistInArray($needle, $array, $key) { for ($i = 0; $i < count($array); $i++) { if ($array[$i][$key] == $needle) { return true; } } return false; } $array = array( array("name" => "apple", "color" => "red"), array("name" => "banana", "color" => "yellow"), array("name" => "orange", "color" => "orange") ); echo isExistInArray("red", $array, "color") ? "存在" : "不存在"; // 存在 echo isExistInArray("green", $array, "color") ? "存在" : "不存在"; // 不存在
array_map 함수 사용
function checkValue($value, $needle) { if ($value == $needle) { return true; } return false; } $array = array( array("name" => "apple", "color" => "red"), array("name" => "banana", "color" => "yellow"), array("name" => "orange", "color" => "orange") ); $result = array_map(function($item) use ($needle) { return checkValue($item["color"], $needle); }, $array); if (in_array(true, $result)) { echo "存在"; } else { echo "不存在"; }
위 내용은 PHP는 그것이 배열의 특정 속성에 있는지 확인합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!