0

I am trying to split an array in a dynamic way, like on the function array_chunk instead of the second parameter int $size to be allowed to add an array like array different_sizes

    $input_sub_arr = range('01', '15');
    $input_sub_array = array();
    foreach ($input_sub_arr as $answer) {
        $input_sub_array[] = 'answer-'.$answer;
    }
    var_Dump($input_sub_array);

$new_answer = array_chunk($input_sub_array, array(5, 6 , 2));
var_dump($new_answer);

1 Answer 1

1

What would be the goal of even doing that? Are you saying you want 3 arrays created, one with 5 items, followed by one with 6, followed by one with 2?

function partition(array $values, array $sizes)
{
    $results = [];
    foreach ($sizes as $size) {
        $current = [];
        while (count($values) > 0 && count($current) < $size) {
            $current[] = array_unshift($values);
        }
        $results[] = $current;
    }
    return $results;
}

$result = partition($input_sub_arr, [5, 6, 2]);
// [['answer-01', 'answer-02', 'answer-03', 'answer-04', 'answer-05'], ['answer-06', 'answer-07', 'answer-08', 'answer-09', 'answer-10', 'answer-11'], ['answer-12', 'answer-13']]
Sign up to request clarification or add additional context in comments.

2 Comments

Yes this is what I am saying
Hey could you have a look here also. I am strugeling for multi dimensional array. stackoverflow.com/questions/40721138/…

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.