所以我有这个功能(里面的内容并不重要,因为它有效),当我在底部打印任何数组时(例如$ stdDevArraycomparison),它可以工作。但是,如果我调用该函数然后尝试打印该数组,则它不会执行任何操作。为什么我不能在调用函数后打印数组?
function TickerResearch ($results, $period, $volinterval) {
for ($x = 2; $x < count($resultscomparison) - 1; $x++) {
$residualsArraycomparison[$x - 2] = round(($resultscomparison[$x] / $resultscomparison[$x + 1]) - 1, 5); // this is the residuals array that I will use for RSI along with the histograms.
}
for ($x = 0; $x < count($residualsArraycomparison) - $period; $x++) {
for ($y = 0; $y < $period; $y++) {
if ($residualsArraycomparison[$x + $y] > 0) {
$upcomparison[$x]++; // no need to define it as 0 beforehand.
}
}
}
for($x = 2; $x < count($resultscomparison) - $period; $x++) {
for ($y = 0; $y < $period; $y++) {
$residualscomparison[$y] = ($resultscomparison[$x + $y] / $resultscomparison[$x + $y + 1]) - 1;
}
$residualsAverage = array_sum($residualscomparison) / count($residualscomparison);
for ($y = 0; $y < $period; $y++) {
$residualsSub[$y] = pow($residualscomparison[$y] - $residualsAverage, 2); // for std dev
$third_moment[$y] = pow($residualscomparison[$y] - $residualsAverage, 3); // for skewness
$fourth_moment[$y] = pow($residualscomparison[$y] - $residualsAverage, 4); // for kurtosis
}
$third_momentSum = array_sum($third_moment);
$fourth_momentSum = array_sum($fourth_moment);
$variance = array_sum($residualsSub) / count($residualsSub);
$stdDevArraycomparison[$x] = pow($variance, 0.5);
$skewnessArraycomparison[$x] = $third_momentSum / (($period - 1) * pow($stdDevArraycomparison[$x], 3)); // | These are both similar. Kurtosis is calculated on
$kurtosisArraycomparison[$x] = ($fourth_momentSum / (($period - 1) * pow($stdDevArraycomparison[$x], 4)) - 3); // | fours while skewness is calculated on threes.
}
for ($x = 0; $x < count($upcomparison); $x++) {
$upArraycomparison[$x] = 100 - 100/(1 + ($upcomparison[$x] / ($period - $upcomparison[$x])));
}
// print_r($stdDevArraycomparison) would work here.
}
TickerResearch($results, $period, $volinterval);
// print_r($stdDevArraycomparison) WON'T work here.
答案 0 :(得分:2)
您需要再次学习函数和变量范围。如果函数不会返回任何东西,那么函数外面是如何知道的。首先,您的函数应该在函数外部返回所需的结果。就像你的函数的最后一个语句应该看起来像
function TickerResearch ($results, $period, $volinterval) {
Blah blah blha
.......
.......
return $stdDevArraycomparison
}
然后抓住结果
$response = TickerResearch($results, $period, $volinterval);
print_r($response) //will print the result
答案 1 :(得分:2)
您无法打印数组,因为您打印变量的引用位于函数之外,正如您所说。这个概念被称为“变量范围”。如果要在函数外部定义相同的变量,则会打印它的值。
以下是"Variable Scope" in the PHP Manual的基本示例:
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
一般来说,大多数语言都实现了局部和全局变量范围的概念。如果变量范围不存在,则不存在局部变量行为。对于可变范围,我们可以在$temp
中命名变量function a()
,在$temp
中命名function b()
。这两个函数将这些变量视为两个独立的数据存储位置,尽管具有相同的人类可读名称。
答案 2 :(得分:0)
答案 3 :(得分:0)
您需要$stdDevArraycomparison
全球。
$stdDevArraycomparison = array();
function TickerResearch ($results, $period, $volinterval) {
global $stdDevArraycomparison;