PHP4用户手册:数据类型->arrays

Arrays

在PHP中一个数组实际上是一个有次序的映射。一个映射是映射值到关键字上。这个类型在单独的方法上被优化的,你可以作为一个真实的数组或一个列表(向量),hashtable (一个映射的执行),字典,聚集,堆栈,队列和更多的来使用它。因为你可能还有另外的PHP-数组作为一个值,你也可以十分容易的模仿树结构。

这个结构的解释超过了这本手册的范围,但是你将发现为这结构的最小的范例。关于这个结构的更多信息,请你查阅其它文献。

语法

array()指定数组

一个数组可以被array() 构造。它由一对key => value并用逗号分割的一系列的号码组成。

一个 key 是任意的非负整数或一个字符串组成。 如果一个是由一个标准的非负整数表达的,它将被解释成这样(i.e. '8' 将被解释成8'08' 将被解释成'08').

一个值可以是任意的。

忽略键。如果你忽略一个键,那么新键将用最大的整数索引加一。如果整数索引也不存在,这个键将是0。如果你已经指定一个值给一个键,那么这个将被复盖。

array( [key =>] value
     , ...
     )
// 键是任意的字符串或非负整数
// 值可以是任意的

用带方括号的语法新建/修改

你可以通过明确的设置值去修改一个已存在的数组。

可以用带方括号的键去分配值给数组。你也可以忽略这个键,在变量名后加一对空方括号。

$arr[key] = value;
$arr[] = value;
// key 是任意字符串或非负整数
// value 可以是任意的
如果 $arr 不存在,它将被新建。如此也可能选择性的去指定一个数组。去改变一个确定的值,刚好分配一个新值给它。如果你想去删除一对键/值,你需要用 unset()

有用的函数

为数组的工作,有一睦有用的函数,参见数组函数 段落。

foreach 流程控制明确提供了一个容易的方法去循环一个数组。

Array do's and don'ts

为什么$foo[bar]是错误的?

在旧的脚本中你可能看到过下边的语法:

$foo[bar] = 'enemy';
echo $foo[bar];
// etc

这是错误的,但它会工作。然而,为什么是错误的呢?在这之后的 syntax 片段中规定,表达式必须在方括号之间。。这意味着你可以象下边一样做:

echo $arr[ foo(true) ];

这个例子使用一个函数的返回值作为数组的索引。PHP也知道是常量,你可以见 E_*

$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";

注意, E_ERROR 是个有效的标识符,刚好象第一个例子中的 bar 。But the last example is in fact the same as writing:

$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";

because E_ERROR equals 1, etc.

Then, how is it possible that $foo[bar] works? It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special keywords.

And, if these arguments don't help: this syntax is simply deprecated, and it might stop working some day.

Tip: When you turn error_reporting to E_ALL, you will see that PHP generates warnings whenever this construct is used. This is also valid for other deprecated 'features'. (put the line error_reporting(E_ALL); in your script)

Note: Inside a double-quoted string, an other syntax is valid. See variable parsing in strings for more details.

Examples

The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.

// this
$a = array( 'color' => 'red'
          , 'taste' => 'sweet'
          , 'shape' => 'round'
          , 'name'  => 'apple'
          ,            4        // key will be 0
          );

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// or simply array('a', 'b', 'c')

Example 6-4. Using array()

// Array as (property-)map
$map = array( 'version'    => 4
            , 'OS'         => 'Linux'
            , 'lang'       => 'english'
            , 'short_tags' => true
            );
            
// strictly numerical keys
$array = array( 7
              , 8
              , 0
              , 156
              , -10
              );
// this is the same as array( 0 => 7, 1 => 8, ...)

$switching = array(         10 // key = 0
                  , 5    =>  6
                  , 3    =>  7 
                  , 'a'  =>  4
                  ,         11 // key = 6 (maximum of integer-indices was 5)
                  , '8'  =>  2 // key = 8 (integer!)
                  , '02' => 77 // key = '02'
                  , 0    => 12 // the value 10 will be overwritten by 12
                  );
                  
<!-- TODO example of
- mixed keys
- overwriting keys
- integer keys as string
- using vars/functions as key/values
- mixed skipping
-->

// empty array
$empty = array();

Example 6-5. Collection

$colors = array('red','blue','green','yellow');

foreach ( $colors as $color ) {
    echo "Do you like $color?/n";
}

/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/

Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:

Example 6-6. Collection

foreach ( $colors as $key => $color ) {
    // won't work:
    //$color = strtoupper($color);
    
    //works:
    $colors[$key] = strtoupper($color);
}
print_r($colors);

/* output:
Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)
*/

This example creates a one-based array.

Example 6-7. One-based index

$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);

/* output:
Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)
*/

Example 6-8. Filling real array

// fill an array with all items from a directory
$handle = opendir('.');
while ($file = readdir($handle)) 
{
    $files[] = $file;
}
closedir($handle);

Arrays are ordered. You can also change the order using various sorting-functions. See array-functions for more information.

Example 6-9. Sorting array

sort($files);
print_r($files);

Because the value of an array can be everything, it can also be another array. This way you can make recursive and multi-dimensional arrays.

Example 6-10. Recursive and multi-dimensional arrays

$fruits = array ( "fruits"  => array ( "a" => "orange"
                                     , "b" => "banana"
                                     , "c" => "apple"
                                     )
                , "numbers" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "holes"   => array (      "first"
                                     , 5 => "second"
                                     ,      "third"
                                     )
                );
阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 这个错误的意思是,在 Python 中只有大小为 1 的数组才能被转换为标量(即单个数字)。这通常意味着你试图将一个数组作为参数传递给一个函数,但这个函数需要的是单个数字,而不是数组。 举个例子,假设你有一个数组 `a` 和一个函数 `f`,你可能会尝试这样调用函数: ``` result = f(a) ``` 如果函数 `f` 需要的是单个数字而不是数组,那么你就会看到这个错误。你可以通过将数组的元素取出来,作为单个数字传递给函数来解决这个问题。例如: ``` result = f(a[0]) ``` 或者,如果你想将整个数组传递给函数,你需要修改函数 `f`,使它能够接受数组作为参数。 希望这能帮到你! ### 回答2: TypeError: only size-1 arrays can be converted to Python scalars(类型错误:只有大小为1的数组才能转换为Python标量)通常出现在使用NumPy进行计算或操作数组时。这个错误通常是由于尝试将长度大于1的数组直接转换为Python标量引起的。 这个错误的原因是,Python标量是一种简单的数据类型,只能存储单个值,而不是数组或矩阵。因此,当尝试将一个长度大于1的数组转换为标量时,就会出现这个错误。 为了解决这个问题,我们需要检查代码中是否有将数组直接转换为标量的地方,并对其进行修改。可以使用数组的元素进行运算,或者使用NumPy的函数来处理数组。 例如,如果我们有一个数组a,我们希望计算它的平均值,我们应该使用NumPy的mean函数来计算,而不是尝试直接将数组转换为标量。 正确的写法是: ``` import numpy as np a = np.array([1, 2, 3, 4, 5]) mean_value = np.mean(a) print(mean_value) ``` 在这个示例中,我们使用了NumPy的mean函数来计算数组a的平均值,而不是直接将数组a转换为标量。这样做可以避免出现TypeError错误。 因此,只有长度为1的数组才能被转换为Python标量,而对于长度大于1的数组,我们应该使用NumPy的函数或运算符来处理它们。 ### 回答3: TypeError: only size-1 arrays can be converted to Python scalars是一种错误类型,它表示只有大小为1的数组才能被转换为Python标量。在使用Python进行科学计算或数据分析时,经常会使用NumPy库来处理数组。当我们使用不同维度的数组进行计算时,可能会遇到这个错误。 这个错误通常出现在将一个多维数组传递给期望接受标量(单个值)的函数或运算符时。例如,当我们尝试将一个多维数组传递给Python内置的数学函数,如math.sqrt()(计算平方根)时,就会出现这个错误。 解决这个错误的方法通常是检查代码中的数据类型和数组维度。可以使用NumPy库的函数来确保我们使用的是标量值,而不是数组。如果我们需要对数组元素逐个进行操作,可以使用循环或向量化的方法来处理。 以下是一个例子,说明如何解决这个错误: ```python import numpy as np # 创建一个多维数组 array = np.array([1, 2, 3]) # 将数组转换为标量(单个值) scalar = np.asscalar(array) print(scalar) # 输出:1 ``` 在这个例子中,我们使用NumPy库的np.asscalar()函数将多维数组array转换为标量(单个值)scalar。通过这个转换,我们就可以避免出现TypeError: only size-1 arrays can be converted to Python scalars错误。 总而言之,TypeError: only size-1 arrays can be converted to Python scalars是由于将多维数组转换为标量(单个值)时出现的错误。要解决这个问题,我们可以使用NumPy库的函数将数组转换为标量,或者检查代码中的数据类型和数组维度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hqywork

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值