doutangtan6386 2016-06-27 05:33
浏览 25

减少多维数组

I have an array that carries a definite number of dimensions so I'm not really looking at something recursive (Unless maybe for maintainability sake in the future). It's a numeric array gotten from the database with each row holding another array. Each of those level 2 arrays contain strings like

var1, var2 , var3

And so on. Note the irregular appearance of commas in the string. So I intend to break the comma delimited string in the third level then log them in the final array but I get an error saying I am supplying an null array. So I want to know why it says the array is null and how I can make it recognise that as a valid array. My code goes below:

function fetch_each($arr) {
$temp = array();

for ($i = 0; $i < count($arr); $i++) {
for ($j = 0; $j < count($arr[$i]); $j++) {
array_reduce(preg_split("/[\s,]+/", $arr[$i][$j]), function($a, $b) {
return array_push($temp, $a, $b);
});
}
}
return $temp;
}

PS: Please don't mark as duplicate. I don't want to copy someone else's code but want to understand why this does not work. Thanks.

  • 写回答

1条回答 默认 最新

  • douliandan7340 2016-07-02 09:15
    关注

    You have this problem because $temp is not visible in the function block. To solve that, you must use the keyword use (variable_name) next to the function definition as in this example :

    array_reduce(preg_split("/[\s,]+/", $arr[$i][$j]), function($a, $b) use (&$temp) {
            return array_push($temp, $a, $b);
    });
    

    Just a remark, $a will contain the result of array_push

    Returns:int the new number of elements in the array.

    So you can remove it from the array_push() instruction to keep a clean array with only splitted strings

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog