Looping through a multi-dimensional array

I have an array that carries a definite number of dimensions so I’m not really looking at something recursive. 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. 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;
}

how does the array look like? in which part of the script does the error occur? did you check the contents at the given part of the array? you can still use explode() and trim() for the csv.

Array looks like this:

array(5) { [0]=> array(1) { [0]=> string(24) "fchvjhv, fyugug, fuyfugf" } [1]=> array(1) { [0]=> string(24) "wehfu, gergergf, gergreg" } [2]=> array(1) { [0]=> string(25) "jbhbkr, rfregre, grewfwre" } [3]=> array(1) { [0]=> string(27) "jgvjgbubk, gregre, fwergwre" } [4]=> array(1) { [0]=> string(25) "uwregerilk, regerg, regew" } }

It occurs in that loop where I’m doing array_push(); on that particular line, it says the array I’m giving it is null. The array I’m giving it is $temp and from code, it clearly is not null.[quote=“chorn, post:2, topic:228432”]
you can still use explode() and trim() for the csv.
[/quote]

Won’t this be longer while still getting the same result? All the same, whichever would get it work seems fine by me.

explode/trim may be more clear but if the regex works thats fine. but for you using a closure, which is a function, which has its own scope, $temp is not available, because you did not pass it as a function parameter, so its null. take the use statement to make it accessible, as mentioned by directrix1 at gmail dot com in the manual of array_Reduce()

If I understood correctly the example below may be enough.

<?php
function fetch_each($arr)
{
    $temp = [];

    for ($i = 0; $i < count($arr); $i++) {
        for ($j = 0; $j < count($arr[$i]); $j++) {
            $temp = array_merge($temp, preg_split("/[\s,]+/", $arr[$i][$j]));
        }
    }

    return $temp;
}

$a = [
  ['1 ,  2, 3'],
  ['a,  b, c', 'x,y,z'],
];

$b = fetch_each($a);

print_r($b);

/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => a
    [4] => b
    [5] => c
    [6] => x
    [7] => y
    [8] => z
)
*/

If you want to loose the loop and don’t mind a temporary variable then this may also work.

function fetch_each($arr)
{
    $temp = [];

    array_walk_recursive($arr, function ($str) use (&$temp) {
        $temp = array_merge($temp, preg_split("/[\s,]+/", $str));
    });

    return $temp;
}
2 Likes

I’ve got a few questions regarding your solution:

How does this work when we clearly do not go down level one? The preg_split should throw a fatal error for being supplied an array instead of a string.

It would if it were being fed a string but it is being fed an array generated by running preg_split on the string to convert it to an array.

Sorry. Please see edited comment.

The preg_split is being fed a string - not an array. It is being run separately on each entry in the array.

It’s because we do go down multiple levels due to array_walk_recursive. This function visits each element in the passed array. If an element is not an array it will be passed to the user defined function. Otherwise it’s passed to array_walk_recursive for iteration. As the documentation says:

Any key that holds an array will not be passed to the function.

In effect all the strings in the structure will be passed to the user defined function regardless of how deep they are buried.

WONDERFUL!!.So there is no need for writing php functions to handle n-dimensional arrays. Thank you for stopping by.

This sort of makes my head spin since I actually tried passing that same value to the method and it complained I was passing it an array instead of a string. All the same, I may just be content with the recursive walk if it would be a pain explaining further. Thank you for stopping by.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.