Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multidimensional array algorithm?

I need to form an multidimensional array as below format however I could not figure out 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 mysql query like below:

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

sample data:

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

php loop is as below:

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

I hope that I will understand multidimensional arrays better with this sample

like image 647
aliaktas Avatar asked Feb 23 '23 09:02

aliaktas


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);
}
like image 144
Poonam Bhatt Avatar answered Feb 24 '23 23:02

Poonam Bhatt


It seemed like all you want is:

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

and $arr will contain your array

After re-reading the question, it seems that it is not exactly the structure you want, but it can simply be turned 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']));
}
like image 33
Jan Dragsbaek Avatar answered Feb 24 '23 21:02

Jan Dragsbaek