1

I am trying to split array data into multiple arrays based on change in data value at known position (column).

$input =  array(
  array(1,2,3),
  array(4,5,3),
  array(7,8,4),
  array(9,10,4),
  array(11,12,4)
);

Here column 3 changes values from 3 to 4 and expected result is to have 2 arrays

$out1 = array(array(1,2,3),array(4,5,3));
$out2 = array(array(7,8,4), array(9,10,4), array(11,12,4));

since number of rows are variable, cannot use array_chunk since column 3 values are variable, cannot use array_filter number of output arrays are also variable. trying splice but failing...

1

2 Answers 2

2

You can use array_reduce to make new array, where index will be equal to last numbers in items

$new = array_reduce($input, function($c, $x) {  $c[$x[2]][] = $x; return $c; }, [] );
$out1 = $new[3];
$out2 = $new[4];

demo

But if array is not sorted and you want to split at points of changing that number, the code can be

$i = -1;
$last = null;
$new = [];
foreach($input as $x) {
    if ($x[2] != $last) {
        $i++;
        $last = $x[2];
    }
    $new[$i][] = $x;
}

demo

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

5 Comments

Yes this works for the regular array as in the question. but not for an array with key=>values like $a = array( array('k1'=>1,'k2'=>2,'k3'=>3), array('k1'=>4,'k2'=>5,'k3'=>3), array('k1'=>7,'k2'=>8,'k3'=>4), array('k1'=>9,'k2'=>10,'k3'=>4) ); where i get Undefined offset: 2 could you clarify
Change $x2 with end($x)
{ $c[end($x)] = $x; return $c; } outputs only the last arrays of each set. demo at . sandbox.onlinephpfunctions.com/code/…
You should add empty square brackets as in my code (i can't write it on this phone :))
0

You can use split index with index of array,

$out1 = $out2 = [];
$splitIndex = 2;
foreach($input as $k => $v){
    if($k < $splitIndex){
        $out1[] = $v;
    }else{
        $out2[] = $v;
    }
}
print_r($out1);
print_r($out2);

Working demo

Output:-

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 3
        )

)
Array
(
    [0] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 4
        )

    [1] => Array
        (
            [0] => 9
            [1] => 10
            [2] => 4
        )

    [2] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 4
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.