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

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料