PHP - Ds Map::toArray() 函式



PHP 的 Ds\Map::toArray() 函式用於將對映轉換為陣列。此函式返回轉換後的陣列,其中包含與對映相同的順序的所有對映元素。

在 PHP 中,陣列是一種資料結構,允許您在單個變數中儲存多個值。

語法

以下是 PHP Ds\Map::toArray() 函式的語法:

public Ds\Map::toArray(): array

引數

此函式不接受任何引數。

返回值

此函式返回一個數組,其中包含與對映相同的順序的所有值。

示例 1

以下演示了 PHP Ds\Map::toArray() 函式的使用:

<?php  
   $map = new \Ds\Map([10, 20, 30, 40, 50]);
   echo "The map elements are: \n";
   print_r($map);
   echo "An array elements are: \n";
   #using toArray() function
   print_r($map->toArray());
?>

輸出

以上程式產生以下輸出:

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

    [3] => Ds\Pair Object
        (
            [key] => 3
            [value] => 40
        )

    [4] => Ds\Pair Object
        (
            [key] => 4
            [value] => 50
        )

)
An array elements are:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)

示例 2

以下是 PHP Ds\Map::toArray() 函式的另一個示例。我們使用此函式將此對映(["Tutorials", "Point", "India"])轉換為陣列:

<?php  
   $map = new \Ds\Map(["Tutorials", "Point", "India"]);
   echo "The map elements are: \n";
   print_r($map);
   echo "An array elements are: \n";
   #using toArray() function
   print_r($map->toArray()); 
?>

輸出

執行以上程式後,它將顯示以下輸出:

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => Tutorials
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => Point
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => India
        )

)
An array elements are:
Array
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)

示例 3

具有非標量鍵的對映無法轉換為陣列。轉換時,此函式將丟擲錯誤。

<?php  
   $map = new \Ds\Map([]);
   $map->put(1, 'a');
   #adding non-scalar value
   $map->put([1, 2, 3], 'e');
   echo "The map elements are: \n";
   print_r($map);
   echo "An array elements are: \n";
   #using toArray() function
   print_r($map->toArray()); 
?>

輸出

執行以上程式後,它將丟擲以下錯誤:

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 1
            [value] => a
        )

    [1] => Ds\Pair Object
        (
            [key] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

            [value] => e
        )

)
An array elements are:
PHP Fatal error:  Uncaught TypeError: 
Cannot access offset of type array on array in C:\Apache24\htdocs\index.php:10
Stack trace:
#0 C:\Apache24\htdocs\index.php(10): Ds\Map->toArray()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 10
php_function_reference.htm
廣告