user3467855 user3467855 - 13 days ago 4
PHP Question

Split multidimensional array with array_chunk based on another array

I am trying to split a multi dimensional array based on another array of values
Something like

array_chunk($multi_array, array(1,3,7))
. Managed to find something related to this over here array_chunk_multi. Just that it doesn't work for multi dimensional array. Currently it splits them up correctly just that I get NULL to all values.

PHP

function array_chunk_array(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;
}

$input_sub_arr = range('1', '6');
$input_sub_array = array();
foreach ($input_sub_arr as $answer) {
$input_sub_array[] = 'answer-'.$answer;
}
$input_sub_answers = array();
foreach ($input_sub_array as $input_sub_answer) {
$input_sub_answers[$input_sub_answer] = array('attributes' => array('correct'));
}
//var_dump($input_sub_answers);
$new_answer = array_chunk_array($input_sub_answers, array(4,2));
var_dump($new_answer);


CURRENT ARRAY

array(6) {
[0]=>
array(3) {
["@attributes"]=>
array(2) {

}
}
[1]=>
array(2) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(1) {

}
}
[2]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
[3]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
[4]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
[5]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
}


EXPECTED OUTPUT

array(4) {
[0]=>
array(3) {
["@attributes"]=>
array(2) {

}
}
[1]=>
array(2) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(1) {

}
}
[2]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
[3]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
}
array(2) {
[1]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {
["@attributes"]=>
array(1) {

}
}
}
[2]=>
array(3) {
["@attributes"]=>
array(2) {

}
["answerText"]=>
array(2) {

}
}
}


CURRENT OUTPUT

array(2) {
[0]=>
array(4) {
[0]=>
NULL
[1]=>
NULL
[2]=>
NULL
[3]=>
NULL
}
[1]=>
array(2) {
[0]=>
NULL
[1]=>
NULL
}
}

Answer

What really should be used here is array_splice:

$vl = [1,1,1,1,2,2,3,3,3];
$sz = [4, 2, 3];
function array_chunk_array(array $values, array $sizes)
{
    $result = [];

    foreach ($sizes as $s) {
        $result[] = array_splice($values, 0, $s);
    }

    return $result;
}

echo'<pre>',print_r(array_chunk_array($vl, $sz)),'</pre>';
Comments