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
广告

© . All rights reserved.