I Want Answers
I Want Answers

Reputation: 441

Reducing a multi-dimensional array

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.

Upvotes: 0

Views: 48

Answers (1)

Navif
Navif

Reputation: 11

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

Upvotes: 1

Related Questions