Rafael Shkembi Rafael Shkembi - 4 months ago 9
PHP Question

Split array into a unspecific number of chuncks

I have a string that contains the given answers from a qiuz by a user. This string is saved on the db table and it has this form.

,P1,1,2,3,5,8,9,,P2,1,3,4,5,6,8,9,,P3,1,2,3,4,6,8,9,,P4,1,,P5a,b,,P5b,d,,P5c,a,,P5d,c,,P6,4,,P7,2,,P8a,hc,,P8b,df,,P8c,bg,,P8d,e,,P9,4,,P10,3,,P11,4,,P12,2,,P13,3,,P14,3,,P15a,acejg,,P15b,dfhib,,P16,1,3,,P17,2,,P18,1,,P19,3,,P20,3,5,6


Ater getting the string i explode it, and the form becomes like this.

Array
(
[0] => P1
[1] => 1
[2] => 2
[3] => 3
[4] => 5
[5] => 8
[6] => 9
[7] => P2
[8] => 1
[9] => 3
[10] => 4
[11] => 5
[12] => 6
[13] => 8
[14] => 9
[15] => P3
[16] => 1
[17] => 2
[18] => 3
[19] => 4
[20] => 6
[21] => 8
[22] => 9
[23] => P4
[24] => 1
[25] => P5a
[26] => b
[27] => P5b
[28] => d
[29] => P5c
[30] => a
[31] => P5d
[32] => c
[33] => P6
[34] => 4
[35] => P7
[36] => 2
[37] => P8a
[38] => hc
[39] => P8b
[40] => df
[41] => P8c
[42] => bg
[43] => P8d
[44] => e
[45] => P9
[46] => 4
[47] => P10
[48] => 3
[49] => P11
[50] => 4
[51] => P12
[52] => 2
[53] => P13
[54] => 3
[55] => P14
[56] => 3
[57] => P15a
[58] => acejg
[59] => P15b
[60] => dfhib
[61] => P16
[62] => 1
[63] => 3
[64] => P17
[65] => 2
[66] => P18
[67] => 1
[68] => P19
[69] => 3
[70] => P20
[71] => 3
[72] => 5
[73] => 6
)


each question starts with a
"P"
. So question 1 will be
"P1"
question 2
"P2"
and so on.

Each given answer is between the
"P"
until next
"P"
.
So the answers given from the user for the question number 1 are
" 1 | 2 | 3 | 5 | 8 | 9 "
.
I was trying to insert the values to another array with a foreach loop but i could not find any way to seperate the answers.

My desire output is.

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

[P2] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 8
[5] => 9
)

)


Please tell me if you have any suggestions.Thank you very much

Answer

assuming we ve everything inside $p

$res= array();
foreach($p as $key => $value){
    if(strpos($value, "P") !== false){
       $currentP = $value;
       $res[$currentP] = array(); 
   }elseif($value){
       $res[$currentP][] = $value;
   }         
}

WORKING PHP FIDDLE tested with v5 and v7