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 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用