array( "apple" => array("/> array( "apple" => array(">

Home  >  Article  >  Backend Development  >  How to get the value of three-dimensional array in php

How to get the value of three-dimensional array in php

PHPz
PHPzOriginal
2023-04-18 14:07:35667browse

In PHP, an array can be nested within another array, thus forming a three-dimensional array. Accessing the elements of a three-dimensional array can be more challenging, but if you are comfortable with array indexing and looping, it will be a breeze.

The method of obtaining the value depends on the structure of the three-dimensional array. Below are two examples where you can get the values ​​of a three-dimensional array.

Example 1: Mixed three-dimensional array

$array = array(
  "fruit" => array(
    "apple" => array(
      "color" => "red",
      "taste" => "sweet"
    ),
    "banana" => array(
      "color" => "yellow",
      "taste" => "sweet"
    )
  ),
  "vegetable" => array(
    "carrot" => array(
      "color" => "orange",
      "taste" => "crunchy"
    ),
    "broccoli" => array(
      "color" => "green",
      "taste" => "bitter"
    )
  )
);

This is a three-dimensional array of mixed values. You can access the nested array by any given key name (fruit or vegetable). For example, if you want to get the color of apple, you can use the following code:

$color = $array["fruit"]["apple"]["color"];

Similarly, if you want to get the flavor of broccoli, you can use the following code:

$taste = $array["vegetable"]["broccoli"]["taste"];

Example 2: Three-dimensional array of numbers

$array = array(
  array(
    array("a1", "b1", "c1"),
    array("a2", "b2", "c2")
  ),
  array(
    array("d1", "e1", "f1"),
    array("d2", "e2", "f2")
  )
);

This is a three-dimensional array composed of numeric keys. You can use a for loop to iterate over an array and use indexing to access elements of nested arrays. For example, if you want to get e1 in an array, you can use the following code:

$e1 = $array[1][0][1];

This is because e1 is in the first nested subarray (index 1) of the second subarray (index 1) of the array 0), whose key is 1.

If you need to convert a three-dimensional array to another format, such as a CSV file or HTML table, iterating over the array and using nested loops to extract the elements can be useful.

To sum up, obtaining values ​​from three-dimensional arrays may be more challenging, but if you master indexing and looping, as well as the structure of the array, it will be a breeze.

The above is the detailed content of How to get the value of three-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn