9

Just wondering if anyone has transformed a 2 dim array to a one dim array in php. I've yet to come across a clear explanation in php. Any suggestion would be appreciated.

5
  • 3
    A little context goes a long way. Commented Aug 2, 2011 at 15:04
  • What is the point of doing this? Do you just want to flatten the array for no apparent reason or do you just no want sub arrays? Or do you have a need for this? Commented Aug 2, 2011 at 15:05
  • I was looking for generic interpretations so other people with similar problems but different context can use. In each slot of this 2d array however, I have 2d points in osm format. The 1d array is for the input of a function i have written Commented Aug 2, 2011 at 15:16
  • There are generic ways to loop through the values of a 2D array and append them sequentially to a new array. However, in cases such as yours, I assume the order of the elements is important. Have you considered writing a wrapper for your existing function that accepts the 2D array and converts it to the specific format required by the existing function? Commented Aug 2, 2011 at 15:21
  • Yes that would be a good solution George. Thanks . However, I would need to change many functions that are interdependent and unfortunately time is of the essence. Commented Aug 2, 2011 at 15:29

7 Answers 7

16

This might be helpful to you if you fetching values from Query here you can use array function which will support in PHP 5.5+

$myfield_arr = array_column($query_result, 'myfield_name');

Say Good bye to loop! Enjoy Smart Code.

Sign up to request clarification or add additional context in comments.

Comments

9

Try this:

function array_2d_to_1d ($input_array) {
    $output_array = array();

    for ($i = 0; $i < count($input_array); $i++) {
      for ($j = 0; $j < count($input_array[$i]); $j++) {
        $output_array[] = $input_array[$i][$j];
      }
    }

    return $output_array;
}

4 Comments

$output_array[] = $input_array[$i][$j]; $output_array has no index value
Assigning a value to an array without supplying an index means that the value will be appended at the end of the array.
Sorry @Doug i did not know that so thanks. I had already written this exactly the same but I thought it would not fill the array but just keep filling to certain number and overwrite slots on each iteration of the for loop. Thanks again for that.
@Doug, don't you need to add $i++ and $j++ at the end of for statements?
1

It depends on what you need but if you want to reduce your 2d array to a 1d curve that completley fills the 2d plane you probably looking for a spatial index or a space-filling-curve. There are some famous and not so known like the z-curve, the hilbert curve, the peano curve or the moore curve. You can write such a curve with a L-system.

Comments

1

Try this one:

function array_to1d($a) {
    $out = array();
    foreach ($a as $b) {
        foreach ($b as $c) {
            if (isset($c)) {
                $out[] = $c;
            }
        }
    }
    return $out;
}

Notice that it includes a test to see if the value is set (non-null). An array that's a transposition of an array with rows of varying length will have null values in some cells, and this check can be helpful if you're trying to linearize such a beast.

Comments

1

After PHP 5.3 there have a new function called arrray_walk_recursive

$data = [1,2,[3,4],5,[6,7,8],9];
$output = [];
array_walk_recursive($data, function($val) use (&$output) {
    $output[] = $val;
});

Notice that the $output is passed by reference

The $output will result in [1,2,3,4,5,6,7,8,9]

Comments

1

Your first thought should be array_reduce() whenever you have lots of something in an array and you just want one something by itself which represents them all in some way.

From the PHP docs:

array_reduce — Iteratively reduce the array to a single value using a callback function

In the case of 2D => 1D array conversion, the something is array; we have lots of them in an array but we just want one of them by itself.

function array2dTo1d($array2d)
{
    return array_reduce($array2d, function($carry, $array) {
        return array_merge($carry, $array);
    }, []);
}

var_dump(array2dTo1d(
    [
        [23423, 5454, 567],
        [4565, 687],
    ]
));

Result:

array(5) {
  [0] =>
  int(23423)
  [1] =>
  int(5454)
  [2] =>
  int(567)
  [3] =>
  int(4565)
  [4] =>
  int(687)
}

Comments

0

The solution for rectangular 2D array is simple indeed, but I had a problem. My 2D-array consisted of 1D arrays of different lengths :

$myArray = [
    [1, 2, 3, 4],
    [5, 6, 7],
    [8, 9]
];

I came up with more generalized solution to turn any 2D array into 1D:

function array2DTo1D($arr2D) {
    $i = 0; $j = 0;
    $arr1D = [];
    while (isset($arr2D[$i][0])) {
        while (isset($arr2D[$i][$j])) {
            $arr1D[] = $arr2D[$i][$j];
            $j++;
        }
        $i++; $j = 0;
    }
    return $arr1D;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.