简体   繁体   English

PHP将数组传递给函数

[英]PHP Passing an Array to a Function

How can I pass an array to a function? 如何将数组传递给函数?

Let's say I have this multi-dimensional array: 假设我有这个多维数组:

$TheArray = (
array("Value 1 0","Value 1 1","Value 1 2"),
array("Value 2 0","Value 2 1","Value 2 2"),
array("Value 3 0","Value 3 1","Value 3 2")
);

Instead of doing this... 而不是这样做...

for ($i=0; $i<=(count($TheArray)-1); $i++)
{
echo $TheArray[$i][0] . " " . $TheArray[$i][1] . " " . $TheArray[$i][2] . "<br />";
}

I want to do this... 我想做这个...

function DoStuffWithTheArray($SubArr)
{
echo $SubArr[0] . " " . $SubArr[1] . " " . $SubArr[2] . "<br />";
}

for ($i=0; $i<=(count($TheArray)-1); $i++)
{
DoStuffWithTheArray($TheArray[$i]);
}

Hopefully, you can tell what I am trying to do, but I do not know how to get it to work. 希望您能说出我要做什么,但我不知道如何使它工作。 When I do try it the way I want, all the values are empty 当我按照自己的方式尝试时,所有值都是空的

I think, you need to learn first how create an array; 我认为,您需要首先学习如何创建数组;

// instead of this
$TheArray = (...
// you can create an array so
$TheArray = array(...

Second, change this style please and see: http://php.net/manual/en/control-structures.foreach.php 其次,请更改此样式,请参阅: http : //php.net/manual/zh/control-structures.foreach.php

for ($i = 0; $i < count($TheArray); $i++)

And answer; 并回答;

$array = array(
    array("Value 1 0", "Value 1 1", "Value 1 2"),
    array("Value 2 0", "Value 2 1", "Value 2 2"),
    array("Value 3 0", "Value 3 1", "Value 3 2")
);

function fn($a) {
    print "$a[0], $a[1], $a[1]\n";
}

foreach ($array as $a) fn($a);
Value 1 0, Value 1 1, Value 1 1
Value 2 0, Value 2 1, Value 2 1
Value 3 0, Value 3 1, Value 3 1

Just pass the array in: 只需将数组传入:

function DoStuffWithTheArray($array) {
    $array[0]...$array[n];
}

That should work. 那应该工作。 Does it not? 不是吗

If you want to alter the content of the array, then you need to pass it by reference: 如果要更改数组的内容,则需要通过引用传递它:

Argument passing by Reference 通过引用传递参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM