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
}
}
array_chunk_array($input_sub_answers, array(4,2));it should bearray_chunk($input_sub_answers, array(4,2));andarray_chunkneed integer but your are given an array as it parameter.array_chunkis mandatory to use here?array_chunk_arraythe version that accept an array as second parameter instead of integer.array_chunk_arrayfunction? could you add this functions functionality?array_unshift?array_unshiftneed first value to prepand. I added2here is demo phpio.net/s/16n9