PHP의 2D 배열
배열은 모든 데이터 유형의 요소 모음입니다. PHP에는 문자열, 정수, 부울, 배열, 개체, 리소스 등과 같은 많은 데이터 유형이 있습니다. 2D 배열은 이러한 데이터 유형을 주로 배열로 혼합한 것입니다. PHP에는 다음과 같은 세 가지 유형의 2D 배열이 있습니다.
광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사무료 소프트웨어 개발 과정 시작
웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등
- 숫자형 배열
- 연관배열
- 다차원 배열
PHP의 2D 배열 유형
이 세 가지 배열은 아래에 설명되어 있습니다.
1. 숫자형 배열
숫자 인덱스가 포함된 배열
구문:
array(value1, value2, value3, …);
예:
$input = array(10,20,30,40,50);
2. 연관 배열
문자열 또는 숫자 인덱스가 있는 배열입니다. 이 배열의 요소는 키-값 쌍의 형태로 저장됩니다.
구문:
array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3',…);
예:
$input = array(0 =>Emma, 1=>Alice, 2=>'John');
3. 다차원 배열
배열의 배열은 다차원 배열이거나 2차원 배열이거나 중첩 배열입니다. 이 형식은 항상 배열 또는 배열입니다. 따라서 중첩 배열이라고 합니다.
구문:
array ( array (elements...), array (elements...), ... )
예:
$input = array( array( "red", "green", "blue" ), array( "yellow", "black", "white" ) );
위 예시에서 입력 배열은 2차원 배열의 예시입니다. 여기서 기본 배열에는 2개의 요소가 포함되어 있으며 각 요소 자체는 3개의 요소로 구성된 배열입니다.
2D 배열을 정의하는 방법
2D 배열에서 값 요소는 추가로 하위 배열을 가질 수 있는 배열이라는 것을 배웠습니다. 배열에 언급된 차원은 행과 열의 형태입니다. 배열의 표 형식을 염두에 두면 이러한 배열을 정의하는 방법을 배우는 것이 더 쉽습니다. 즉, 2차원 배열이면 2개의 인덱스가 사용되고, 3차원 배열이면 3개의 인덱스가 사용되는 식입니다.
2D 배열을 만드는 방법
2D 배열을 정의하는 방법을 알았으므로 이제 만들 수 있습니다. 여기서 인덱스는 정의되지 않으며 기본적으로 항상 0으로 시작하는 숫자입니다.
$input=array( array( "red", "green", "blue" ), array( "yellow", "black", "white" ) );
연관배열 형태로도 배열을 정의할 수 있습니다.
(in key =>value form)
인덱스 또는 키는 색상, 과일, 자동차와 같은 문자열입니다. 값 요소는 각각 3개의 요소를 포함하는 배열 형식입니다.
$input = array( 'colors'=>array ("Red", "Green", "Blue"), 'fruits'=>array ("Apple", "Orange", "Grapes"), 'cars'=>array ("BMW", "Skoda", "Mercedes") );
2D 배열 요소에 액세스하는 방법
이러한 배열 값에 액세스하려면 대괄호를 사용할 수 있습니다. 2D 배열의 더 많은 레벨에 들어가면서 각 레벨마다 대괄호 세트의 사용이 증가합니다.
예시 #1
코드:
$input = array ( 'colors' =>array ("Red", "Green", "Blue"), 'fruits' =>array ("Apple", "Orange", "Grapes"), 'cars' =>array ("Skoda", "BMW", "Mercedes") );
첫 번째 대괄호 세트에는 색상, 과일, 자동차라는 키가 포함되어 있다는 점을 기억하세요. 그 뒤에는 다음 레벨로 이동하기 위한 대괄호 세트가 하나 더 있으며 0,1,2와 같은 숫자로 액세스할 수 있습니다.
위 배열의 "Grapes" 요소에 액세스하려면
echo $input['fruits'][2];
다음 예시도 유사
배열의 "Mercedes" 요소에 액세스하려면
echo $input['cars'][2];
배열의 "Red" 요소에 액세스하려면
echo $input['colors'][0];
배열에서는 인덱스가 항상 0으로 시작합니다.
예시 #2
코드:
$input = array ( array ("Red", "Green", "Blue"), array ("Yellow", "Orange", "Purple"), );
위 배열의 "Orange" 요소에 액세스하려면 다음 줄을 사용합니다
echo $input[0][1];
'녹색'을 부여합니다
echo $input[1][2];
“보라색”을 드립니다
echo $input[0][0];
“빨간색”을 부여합니다
PHP에서 2D 배열 요소를 삽입하는 방법은 무엇입니까?
배열 요소를 정의하고 생성하고 액세스하는 방법을 알았으므로 이제 배열에 요소를 삽입하는 방법을 배우겠습니다. 삽입할 array_push() 함수, 제거할 array_shift() 함수 등과 같이 다차원 배열에서 작동하도록 PHP에 정의된 배열 함수가 있습니다.
$input = array ( 'colors'=>array ("Red", "Green", "Blue"), 'fruits'=>array ("Apple", "Orange", "Grapes"), 'cars'=>array ("Skoda", "BMW", "Mercedes") );
print_r() 함수를 사용하여 먼저 배열을 있는 그대로 인쇄해 보겠습니다.
코드:
//create multidimensional array $input = array ( "colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); // print the multidimensional array echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
출력:
이제 사용할 과일 하위 배열에 요소를 추가합니다
array_push() function
구문:
array_push(array, value1,value2...)
어디,
- 배열은 $input 배열입니다
- value1은 배열에 추가할 요소입니다
- 값2, 값3은 선택사항입니다
예시 #1
코드:
$input = array ( "colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); array_push($input['colors'], "Black"); echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
출력:
아래 프로그램에서는 "colors" 키를 제거하고 출력 이미지에 표시된 대로 0 키를 사용하여 지정된 배열의 마지막에 추가되는 것을 확인했습니다.
Example #2
Code:
// create multidimensional array $input = array ( "colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); // adding a value to array array_push($input, "Black"); // print the multidimensional array echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
Example #3
Code:
//create multidimensional array $input = array ( array ("Red", "Green", "Blue"), array ("Yellow", "Orange", "Purple") ); //add a color to the array array_push($input, "Black"); // print the multidimensional array echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
How to Update Elements of 2D Arrays in PHP?
To update an element of the 2D array just get the key from the array and replace the value of that key in a particular array.
$input['cars']['Mercedes'] = 'Duster';
Example #1
Code:
//create multidimensional array $input = array ( "colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); //update the Mercedes with Duster $input["cars"][2] = "Duster"; // print the multidimensional array echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
Example #2
Code:
//create multidimensional array $input = array ( array ("Red", "Green", "Blue"), array ("Yellow", "Orange", "Purple") ); //update the Mercedes with Duster $input[0][1] = "White"; // print the multidimensional array echo "<pre class="brush:php;toolbar:false">"; print_r($input); echo "<pre class="brush:php;toolbar:false">";
Output:
How to Delete Elements of 2D Arrays?
To delete an element of the 2D array we will use array_shift() function.
array_shift removes and returns the first element value of the array.
Syntax:
array_shift(array)
where
-array is the $input array
Example #1
Code:
//create multidimensional array $input = array ( "colors"=>array ("Red", "Green", "Blue"), "fruits"=>array ("Apple", "Orange", "Grapes"), "cars"=>array ("Skoda", "BMW", "Mercedes") ); //print the removed element print_r(array_shift($input));
Output:
Example #2
Code:
//create multidimensional array $input = array ( array ("Red", "Green", "Blue"), array ("Yellow", "Orange", "Purple") ); //print the removed element print_r(array_shift($input));
Output:
Two dimensional in Associative Array
In the following example, we have created a 2-d array containing the information of books like the author of the book, type of book, and published in the year. Also, we will learn how to traverse or loop through this array. Looping through the multidimensional array we will use a nested foreach loop. Meaning one foreach loop inside another foreach loop. The same can also be done using for loop.
$input = array( "The_Alchemist" => array ( "author" => "Paulo Coelho", "type" => "Fiction", "published_year" => 1988 ), "Managing_Oneself" => array ( "author" => "Peter Drucker", "type" => "Non-fiction", "published_year" => 1999 ), "Measuring_the_World" => array( "author" => "Daniel Kehlmann", "type" => "Fiction", "published_year" => 2005 ) );
Just printing the above array without any loop will give us the following output:
Code:
// create multidimensional array $input = array( "The_Alchemist" => array ( "author" => "Paulo Coelho", "type" => "Fiction", "published_year" => 1988 ), "Managing_Oneself" => array ( "author" => "Peter Drucker", "type" => "Non-fiction", "published_year" => 1999 ), "Measuring_the_World" => array( "author" => "Daniel Kehlmann", "type" => "Fiction", "published_year" => 2005 ) ); // print the plain multidimensional array echo ""; print_r($input); echo "";
Output:
Now we will print the multidimensional array using a foreach loop.
Code:
// create multidimensional array $input = array( "The_Alchemist" => array ( "author" => "Paulo Coelho", "type" => "Fiction", "published_year" => 1988 ), "Managing_Oneself" => array ( "author" => "Peter Drucker", "type" => "Non-fiction", "published_year" => 1999 ), "Measuring_the_World" => array( "author" => "Daniel Kehlmann", "type" => "Fiction", "published_year" => 2005 ) ); //foreach to loop the outer array foreach($input as $book) { echo "
"; // foreach to loop the inner array foreach($book as $key=>$value) { echo $key." ". $value. "
"; } }
Output:
Conclusion
I hope this article is helpful to learn the concepts of the topic on a 2D array in PHP. This topic covers all the concepts required for the understanding related to the 2D array in PHP. This topic is made simpler with the help of examples with the output snapshots to refer to. According to the article, if all the programs are practiced well will surely help you to grasp the concepts easily. I hope the topic is made more informative for gaining more knowledge.
위 내용은 PHP의 2D 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

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

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

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

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

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

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP와 Python은 고유 한 장점과 단점이 있으며 선택은 프로젝트 요구와 개인 선호도에 달려 있습니다. 1.PHP는 대규모 웹 애플리케이션의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 데이터 과학 및 기계 학습 분야를 지배합니다.
