PHP多维数组算法



我需要形成如下格式的多维数组,但我无法找出算法

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")))

数据来自mysql查询,如下所示:

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

样本数据:

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

php循环如下:

do {
//whatever I tried here failed :(
} while ($t = mysql_fetch_assoc($r_tav));
我希望通过这个示例我能更好地理解多维数组

$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);
}

似乎你想要的只是:

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

$arr将包含数组

重读问题后,它似乎不是你想要的结构,但它可以简单地变成:

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']));
}

相关内容

  • 没有找到相关文章

最新更新