PHP multidimensional array algorithm?

I need to form a multidimensional array as shown below in the format, however I could not understand the algorithm

array( [0]=>array( "id"=>"1","data"=>array([0]=>array("kid"=>"434","k"=>"Ali","m"=>"msj1"), [1]=>array("kid"=>"344","k"=>"Dali","m"=>"msj3")), [1]=>array( "id"=>"2","data"=>array([0]=>array("kid"=>"347","k"=>"Cenk","m"=>"msj2"), [1]=>array("kid"=>"345","k"=>"Tan","m"=>"msj4"))) 

The data comes from a MySQL query, as shown below:

CHOOSE kid, k, m, id FROM table1 WHERE rid = 1 ORDER BY (id)

Sample data:

 id kid km 1 434 Ali msj1 2 347 Cenk msj2 1 344 Dali msj3 2 345 Tan msj4 

Php loop as below:

 do { //whatever I tried here failed :( } while ($t = mysql_fetch_assoc($r_tav)); 

I hope that with this pattern I better understand multidimensional arrays

+4
source share
2 answers
 $arrRows = mysql_fetch_array($r_tav); $arrRowData = array(); $arrRowDataFinal = array(); foreach ($arrRows as $key => $value){ $arrRowData[$value['id']][] = array("kid"=>$value['kid'],"k"=>$value['k'],"m"=>$value['m']); } foreach($arrRowData as $key => $value){ $arrRowDataFinal[] = array('id' => $key, 'data' => $value); } 
+4
source

It seemed that all you need is:

 while ($t = mysql_fetch_assoc($r_tav)){ $arr[] = $t; } 

and $arr will contain your array

After reading the question again, it seems that this is not quite what you need, but you can simply turn it into:

 while ($t = mysql_fetch_assoc($r_tav)){ $arr[] = array('id' => $r_tav['id'], 'data' => array('kid' => $r_tav['kid'], 'k' => $r_tav['k'], 'm' => $r_tav['m'])); } 
+4
source

Source: https://habr.com/ru/post/1381874/


All Articles