>  기사  >  백엔드 개발  >  PHP의 다차원 배열

PHP의 다차원 배열

WBOY
WBOY원래의
2024-08-29 12:44:25266검색

다차원 배열은 특별한 것이 아니라 다른 배열 내부의 배열입니다. 배열의 각 인덱스는 또 다른 배열이나 특정 요소를 가리킬 수 있는 단일 요소 대신 다른 배열을 보유합니다. 배열 내부의 이러한 하위 배열은 외부 배열에서 시작하여 내부 배열을 향해 이동하는 다중 차원을 사용하여 액세스됩니다. 차원은 기본적으로 배열의 특정 위치에 있는 값에 액세스하거나 저장하는 데 필요한 인덱스입니다. PHP의 다차원 배열은 실시간 응용 프로그램에서 많이 사용되지만 여러 대괄호와 함께 작업하기 위한 약간의 복잡성(값에 액세스하거나 값을 저장하는 등)으로 인해 이를 1차원 배열과 비교하여 처리하는 것은 매우 까다롭습니다. 특정 인덱스를 사용하려면 루프를 사용해야 합니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

다음은 PHP의 다차원 배열의 일반적인 구문입니다. PHP의 다차원 배열은 2D, 3D, 4D 등이 될 수 있습니다. 다차원 배열일수록 관리하기가 더 어렵고, 배열 이름 앞에 괄호가 더 많이 추가됩니다.

2D 배열 구문:

array(
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
)

3D 배열 구문:

array(
array (
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
),
array (
array(element1, element2, elements3, ...),
array(element1, element2, elements3, ...),
… so on
),
… so on
)

PHP에서 다차원 배열을 선언하는 방법

PHP에서는 다차원 배열을 색인화하거나 연관시킬 수 있습니다. 연관 배열은 인덱스 배열에 비해 더 대화형입니다. PHP에서는 '배열' 키워드를 사용하여 PHP에서 다차원 배열을 선언하는 매우 간단한 방법을 허용합니다. 다른 배열 안에 배열을 선언하려면 'array'라는 키워드를 추가한 다음 해당 배열의 요소를 추가해야 합니다.

1. PHP에서 2차원 배열 선언

코드:

<?php
$employee_details = array();
$employee_details[ ] = array("Ram", "Agra", "Sr. Engineer");
$employee_details[ ] = array("Raghav", "Delhi", "Jr. Engineer");
?>

또는

<?php
$employee_details = array(
array("Ram", "Agra", "Sr. Engineer"),
array("Raghav", "Delhi", "Jr. Engineer"),
);
?>

위에 표시된 두 번째 방법은 이해하기 쉽기 때문에 일반적으로 사용됩니다.

2. PHP에서 3D 배열 선언

코드:

<?php
/* Simplest way to declare a  3D array in Php in an indexed manner */
$item_details  = array(
array(
array ("item1", "abc", 100)),
array ("item2", "bcd", 200)),
array ("item3", "def", 300)),
),
array(
array ("item4", "abc4", 100)),
array ("item5", "bcd5", 200)),
array ("item6", "def6", 300)),
),
);
?>

위 선언은 연관에 사용된 키-값 쌍이 없으므로 순전히 3D 배열 중 하나로 색인화된 것입니다.

PHP에서 다차원 배열을 초기화하는 방법은 무엇입니까?

다차원 배열을 초기화한다는 것은 배열의 특정 위치나 인덱스에 값이나 요소를 할당하는 것을 의미합니다. PHP에서 다차원 배열을 초기화하는 것은 선언하는 것만큼 쉽습니다. 명심해야 할 유일한 것은 하위 배열을 초기화하는 동안 중괄호를 사용하는 것입니다. 다차원 배열의 값을 초기화하는 동안 기본 배열은 인덱싱되거나 연관될 수 있습니다. 아래 예제에서 기본 배열은 Levis, Lee, Denizen 등과 같은 키를 갖는 연관 배열입니다.

1. PHP에서 2D 배열 초기화

코드:

<?php
/* It is a multidimensional 2D array of clothes in which the main array holds another arrays of having 2 elements like cloth type and quantity */
/* It is associative kind of array having the data in the form of key => value pairs. So the data at the inner subarray is represented as associated by the key element.*/
$clothes = array(
"Levis" =>     array(
"Cloth_type" => "jeans",
"Quantity" => 20
),
"Pepe" =>        array(
"Cloth_type" => "jeans",
"Quantity" => 100
),
"Lee" =>      array(
"Cloth_type" => "tshirts",
"Quantity" => 50
),
"Denizen" =>   array(
"Cloth_type" => "tops",
"Quantity" => 80
)
);
?>

2. PHP에서 3D 배열 초기화

3D 배열의 초기화는 2D 배열과 동일하며 둘 사이의 유일한 차이점은 크기입니다. 3D 배열은 2D 배열보다 초기화하는 데 인덱스가 1개 더 필요합니다. 배열의 크기가 증가할수록 이를 초기화하는 인덱스의 수도 증가합니다. 아래 예에서 기본 배열은 자체적으로 하위 배열을 포함하는 간단한 인덱스 배열입니다. 또한 아래 예의 기본 배열을 브랜드 이름으로 키를 사용하여 2D 배열에서 수행한 것처럼 연관 배열로 만들 수 있으므로 고객이 액세스하고 저장하는 동안 더 쉽게 이해할 수 있습니다.

코드:

<?php
/* In this there is a 3D array of clothes in which each element have an array of cloth type, brand and quantity of that particular brand. Each brand has different quantity and cloth type.*/
$clothes = array(
array(
array(
"Brand" => "Levis",
"Cloth_type" => "jeans",
"Quantity" => 20
),
array(
"Brand" => "Levis",
"Cloth_type" => "Tops",
"Quantity" => 100
)
),
array(
array(
"Brand" => "Lee",
"Cloth_type" => "jeans",
"Quantity" => 50
),
array(
"Brand" => "Lee",
"Cloth_type" => "tops",
"Quantity" => 80
)
),
);
?>

PHP에서 다차원 배열에 액세스

PHP에서 다차원 배열에 액세스하는 것은 매우 간단하며 PHP에서 일반적으로 사용되는 루프인 for 또는 foreach 루프를 사용하여 수행됩니다. 인덱스 배열의 경우 C, Java 등 다른 언어와 유사하게 행 및 열 번호를 사용하여 배열 요소에 정상적으로 접근할 수 있습니다(arr[row_Num][column_Num]).

연관 배열의 경우 다차원 배열 요소에 대한 액세스는 키와 값 쌍(키 => 값)을 사용하여 수행됩니다. 요소는 간단한 for 또는 for Each 루프를 통해 액세스됩니다. 다차원 배열의 요소 접근을 명확하게 이해하려면 아래 예제를 참조하세요.

종류

다차원 배열이 PHP에 존재할 수 있는 특정 상태는 없습니다. 특정 상황과 시나리오에 따라 다릅니다. 배열의 크기는 그에 따라 달라집니다. 일반적으로 프로그래머들은 2차원 배열과 3차원 배열을 사용하는데, 3차원 배열 이후에는 관리하기가 좀 어렵기 때문입니다.

As we have understood the declaration, initialization and accessing of multidimensional arrays in PHP, it is time for a quick brief explanation with examples.

1. 2D Array in PHP

2D arrays are basically array inside another array. Consider a scenario that a user have 10 books and each book has a different name, cost, type. In this case, the programmer can create an array of book numbers and each element of the main array holds the array which contains details of the book like name, cost, and type.

Code:

<!DOCTYPE html>
<html>
<body>
<?php
/* Multidimensional 2D array for 4 books and each book having a different array containing book name, cost and type. */
$books = array(
array("Fiction ", "Action and Adventure ", 800),
array("Fiction ", "Anthology ", 1000),
array("Non- Fiction ", "Biography ", 600),
array("Non- Fiction ", "Cook Book ", 900)
);
/* Accessing of a 2D array with the row_number and column_number */
for ($row_num = 0; $row_num < 4; $row_num++) {
echo "<p>Book number is  $row_num</p>";
for ($col_num = 0; $col_num < 3; $col_num++) {
// Accessing a particular element in a 2D array
echo $books[$row_num][$col_num];
}
echo "<br>";
}
?>

Output:

PHP의 다차원 배열

2. 3D Array in PHP

3D arrays are an extension of 2D arrays. 3D arrays contain one more dimension and provides the chance to add more detailed information. Consider a scenario of employee array, in which employee have name, company and year and each employee has a company profile with the attributes id, skills, and profile. Each employee has personal data also with the details of the city, state, and country. In Order, to Store, the Above Data 3D Array Would Be Required.

Code:

<!DOCTYPE html>
<html>
<body>
<?php
$Employee = array(array(array("name", "company", "year"),
array("id","skills","profile"),
array("city","state","country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
<?php
echo "<ul>";
for ( $outermost = 0; $outermost < 3; $outermost++ )
{
echo "<li>The outermost number $outermost";
echo "<ul>";
for ( $row_num = 0; $row_num < 2; $row_num++ )
{
echo "<li> Now displaying the row number $row_num";
echo "<ul>";
for ( $col_num = 0; $col_num < 3; $col_num++ )
{
// accessing the array elements in a 3D array
echo "<li>".$Employee[$outermost][$row_num][$col_num]."</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
echo "</li>";
}
echo "</ul>";
?>
</body>
</html>

Output:

PHP의 다차원 배열

The above example clearly displays the details of the employee along with their skills in a very user-friendly manner. It allows the detailing of each and every employee in a fancy 3d arrays. We are dealing with 3d arrays, in order to access that, we need to first reach to the main array and then to the index which again holds the subarray and then to the elements of its subarray. In this way, accessing to the elements works in the case of multidimensional arrays starting from the outermost to the innermost array. similarly, in real life, there are sub-arrays or detailed things in which multidimensional arrays are used.

Conclusion

The above explanation clearly shows how the multidimensional arrays are used in php along with their basic syntax and initialization. Multidimensional arrays play an important role when it comes to working on real-life problems as they allow the user to store the data in a detailed form. Moreover, as shown above, php allows storing the multidimensional data either in indexed or associative form according to the requirements which makes it more friendly to access and store the data.

위 내용은 PHP의 다차원 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP의 연관 배열 다음 기사:PHP의 연관 배열