1

Suppose that I start with an array that looks like:

$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));

For simplicity, assume that I have a rule that says: delete the first subarray and then delete the first elements of the remaining subarrays. This would yield the result:

$new_array  = array(array(4,5), array(6,7))

Then assume I expand the problem to larger arrays like:

$array_2 = array(array(1,2,3,4), array(2,3,4,5), array(3,4,5,6), array(4,5,6,7));

I have the same rule here - delete first subarray and then delete first elements of the remaining subarrays. BUT this rule must be continued until the smallest subarray contains only two elements (as in the first example). So that in stage one of the process, my new array would look like:

$new_array_s1 = array(array(3,4,5), array(4,5,6), array(5,6,7));

But in the final stage, the completed array would look like:

$new_array_s2 = array(array(5,6), array(6,7));

For context, here is my code for the $array_1 example:

<?php

$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));
$array_shell = $array_1;
unset($array_shell[0]);
$array_size = count($array_shell);

$i = 0;
$cofactor = array();

while($i < $array_size) {
$el_part_[$i] = $array_1[$i];
unset($el_part_[$i][0]);
$el_part_[$i] = array_values($el_part_[$i]);
array_push($cofactor, $el_part_[$i]);

++$i;
}

echo '<pre>',print_r($cofactor,1),'</pre>';

?>

My Question: How can I generalise this code to work for N sized arrays?

3 Answers 3

3

You don't need a complicated code .. Just loop and use array_shift

Example:

print_r(cleanUp($array_1));

Function

function cleanUp($array) {
    array_shift($array);
    foreach($array as $k => $var) {
        is_array($var) && array_shift($array[$k]);
    }
    return $array;
}

See Live DEMO

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

Comments

1
$num = count($array_1);
for($i=0;$i<=$num;$i++)
{
if($i==0)
unset($array_1[$i]);
else unset($array_1[$i][0]);
}

Comments

1

Building off of Baba's answer, to work with N element arrays (assuming each array contains the same number of elements):

<?php
$array_1 = array(array(1,2,3,4), array(2,4,5,6), array(3,6,7,8));

$array = $array_1;
while(count($array[0]) > 2)
  $array = cleanUp($array);

print_r($array);

    function cleanUp($array) {
        array_shift($array);
        foreach($array as $k => $var) {
            is_array($var) && array_shift($array[$k]);
        }
        return $array;
    }

This will keep reducing until the sub-arrays have only 2 elements.

-Ken

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.