如何在php中返回数组?实际上,我想返回$x[]
的整个值,而不是$x[]
的最后一个索引。请帮帮我…
<?php
function top() {
require './php/connection.php';
$sql = "SELECT * FROM tbl_add";
$query = mysqli_query($connect, $sql);
$n = 0;
while ($result = mysqli_fetch_assoc($query)) {
$a[$n] = $result['add_id'];
$n = $n + 1;
}
$n = $n - 1;
for ($j = 0; $j < $n; $j++) {
for ($i = 0; $i < $n - 1 - $j; $i++) {
if ($a[$i] > $a[$i + 1]) {
$tmp = $a[$i];
$a[$i] = $a[$i + 1];
$a[$i + 1] = $tmp;
}
}
}
for ($i = 0; $i <= $n; $i++) {
echo $a[$i] . '<br>';
}
$j = 1;
for ($i = 0; $i <= 5; $i++) {
$r = $a[$i];
$sql = "SELECT * FROM tbl_add WHERE add_id='$r'";
$query = mysqli_query($connect, $sql);
$result = mysqli_fetch_assoc($query);
if ($result) {
$x[] = $result['mail'];
return $x[];
}
}
}
?>
return $x[];
是无效语法。
在表达式$x[] = $result['mail'];
中,$x[]
并不意味着"$x
的最后一个元素"。这只是PHP的一个好处,它使程序员不用编写$x[count($x)]
1。
返回数组和return $x;
一样容易(假定$x
是array
)。
顺便说一句,在代码中没有$x
初始化为数组的地方。您只需使用数组语法将值添加到某个不存在的变量中。PHP可以帮助您,首先创建一个数组并将其存储在$x
变量中,但强烈反对这种做法。在第一次使用$x
之前,您应该在某个位置添加$x = array();
(当然是在循环之外)。例如,可以将其放在for ($i = 0; $i <= 5; $i++) {
行之前。`
1这句话并不完全正确。但是,如果仅使用$x[] = ...
语法将值添加到数组中(就像发布的代码中发生的那样),那么它是正确的。
您必须返回$x
然后当你调用这个函数$data = top();
现在您可以将函数top的返回数据返回到变量名data
// the code below will return $x as it is, independent of what it is. Array, integer, string etc..
Return $x;
// if you need to return two values use:
Return array($x, $y);
// again bit variables are returned as they are.
要调用函数并获取值/数组,请使用:
$array = top();
Var_dump($array); //should be $x from your function