日期:2014-05-17  浏览次数:20695 次

三维数组插入数据库问题
$arrData = array(
'manager' =>'5',
'blogname' => '博客',
'domain' => 'bokee',
'user[1]'=>array('uid' => 1,'name'=>'zhangsan'),
'user[2]'=>array('uid'=>2,'name' => 'lisi'),
);
这个数组中的'manager','blogname','domain'要插到一个表中,而user[]要插到另一个表中,user[]还可能3,4,5.....请问这样要怎么做?谢谢了

------解决方案--------------------
PHP code

$arrData = array(
'manager' =>'5',
'blogname' => '博客',
'domain' => 'bokee',
'user[1]'=>array('uid' => 1,'name'=>'zhangsan'),
'user[2]'=>array('uid'=>2,'name' => 'lisi'),
);
foreach($arrData as $value){
    if(gettype($value) === 'array'){
        echo $value['uid'];
        echo $value['name'];
    }
}

------解决方案--------------------
程序员对程序有百分百的控制权啊.
------解决方案--------------------
楼主,那是二维数组:
PHP code

$arrData = array(
'manager' =>'5',
'blogname' => '博客',
'domain' => 'bokee',
'user[1]'=>array('uid' => 1,'name'=>'zhangsan'),
'user[2]'=>array('uid'=>2,'name' => 'lisi'),
);

#这是二维数组
foreach($arrData as $k=>$data){
    if(is_array($data))
        $user[] = $data;
    else
        $arr[$k] = $data;
}
print_r($arr);
#Array ( [manager] => 5 [blogname] => 博客 [domain] => bokee )
print_r($user);
#Array ( [0] => Array ( [uid] => 1 [name] => zhangsan ) [1] => Array ( [uid] => 2 [name] => lisi ) )

------解决方案--------------------
这个就写1个 插入方法 和 字段生成方法吧.
先把 2个数组拆分
随手打的 可能有错误, 自己调整下。
PHP code

$arrData = array(
'manager' =>'5',
'blogname' => '博客',
'domain' => 'bokee',
'user[1]'=>array('uid' => 1,'name'=>'zhangsan'),
'user[2]'=>array('uid'=>2,'name' => 'lisi'),
);
$data1 =array('manager' =>'5','blogname' => '博客','domain' => 'bokee',);
$data2 =(array)$arrData['user'];

//data1 我们就不说了.
function add($data,$table)
{
   foreach($data as $v){
   $key = implode('`,`',array_keys($v));
   $key = '`'.$key.'`';
   $value = implode("','",array_values($v));
   $value = "'".$value ."'";
   if(!$res = create($key,$value,$table))
   {
        return $res;
   }
   }
   //生成结果:uid,name
}
function create($key,$value,$table){
    insert into $table($key) values($value)
}