当前位置:Gxlcms > PHP教程 > 对数组进行分组

对数组进行分组

时间:2021-07-01 10:21:17 帮助过:65人阅读

我现在想实现这么个功能,
Array ( [tag] => id[type] => complete [level] => 4 [value] => 01 )
Array ( [tag] => name[type] => complete [level] => 4 [value] => 小张 )
Array ( [tag] => flag[type] => complete [level] => 4 )
Array ( [tag] => id [type] => complete [level] => 4 [value] => 02 )
Array ( [tag] => name [type] => complete [level] => 4 [value] => 小李 )
Array ( [tag] => flag [type] => complete [level] => 4 )
Array ( [tag] => id [type] => complete [level] => 4 [value] => 03 )
Array ( [tag] => name [type] => complete [level] => 4 [value] => 小刘 )
Array ( [tag] => flag [type] => complete [level] => 4 )

这几个数组是我通过解析xml文件得到打印出来的,他们每三个数组是一组,我需要把id, name, flag写入数据库,以上这种情况就是写三条数据进数据库。但是我取得的xml文件不固定,内容也不固定,所以每次不一定就是三个一组,我想做个通用的方法,把数组分类,然后循环存入数据库有什么好办法吗?各位大神?


回复讨论(解决方案)

$a = array(  Array ( 'tag' => 'id',   'type' => 'complete', 'level' => 4, 'value' => '01' ),  Array ( 'tag' => 'name', 'type' => 'complete', 'level' => 4, 'value' => '小张' ),  Array ( 'tag' => 'flag', 'type' => 'complete', 'level' => 4, ),  Array ( 'tag' => 'id',   'type' => 'complete', 'level' => 4, 'value' => '02' ),  Array ( 'tag' => 'name', 'type' => 'complete', 'level' => 4, 'value' => '小李' ),  Array ( 'tag' => 'flag', 'type' => 'complete', 'level' => 4, ),  Array ( 'tag' => 'id',   'type' => 'complete', 'level' => 4, 'value' => '03' ),  Array ( 'tag' => 'name', 'type' => 'complete', 'level' => 4, 'value' => '小刘' ),  Array ( 'tag' => 'flag', 'type' => 'complete', 'level' => 4, ),);$st = array();foreach($a as $t) {  if(isset($st[$t['tag']])) {    //完成你需要的操作    $st = array();  }  $st[$t['tag']] = $t;}
应该看得懂吧

我试了一下楼上的做法,稍微有点问题,我换了个方法,暂时解决了,不过也给你分吧,谁让你是唯一一个回答我问题的捏~~~

人气教程排行