按数组值分组

时间:2011-09-26 14:35:45

标签: php post group-by grouping

我正在使用此代码:

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
foreach($permissions as $permission) {
  for ($i = 1; $i <= 5; $i++) {
    $mode = $_POST['permission'][$i][$permission];
    if($mode == 1) 
      echo "{$permission} = {$i}:::";
  }
}

如果我检查一些复选框,输出是:

canview = 1:::canview = 5:::canpostreplies = 3:::canpostpolls = 5:::

我不想输出:

而不是canview = 1:::canview = 5:

canview = 1,5

如果我有例如:

canpostpolls = 1:::canpostpolls = 2:::canpostpolls = 3

这将是:

canpostpolls = 1,2,3:::canview = 1,5

我希望你能理解这些人。这是我自己的想法,你可以自由地与我分享你的想法,这些数据将被导出到mysql表。

4 个答案:

答案 0 :(得分:2)

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$setpermissions = array();
foreach($permissions as $permission) {
  for ($i = 1; $i <= 5; $i++) {
    $mode = $_POST['permission'][$i][$permission];
    if($mode == 1) {
      if (!isset($setpermissions[$permission])) {
         $setpermissions[$permission] = array();
      }
      $setpermissions[$permission][] = $i;
    }
  }
}
$plist = array();
foreach ($setpermissions as $name => $sp) {
   $plist[] = "$name = " . implode(',', $sp);
}
echo implode(':::', $plist);

答案 1 :(得分:0)

您需要更多地过滤数据...可能是这样的:

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$filtered_perms = array();
foreach($permissions as $permission) {
  for ($i = 1; $i <= 5; $i++) {
    $mode = $_POST['permission'][$i][$permission];
    if($mode == 1) {
       if(!is_array($filtered_perms[$permission])) {
         $filtered_perms[$permission] = array();
       }
       $filtered_perms[$permission][] = $i;
  }
}

然后,您可以执行以下操作:

 $final_perms = array();
 foreach($filtered_perms as $key => $val) {
      $final_perms[$key] = implode(",", $val);
  }

希望有所帮助!

答案 2 :(得分:0)

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
$userPermissions = array();
foreach($permissions as $permission) {
  for ($i = 1; $i <= 5; $i++) {
    $mode = $_POST['permission'][$i][$permission];
    if($mode == 1) 
      $userPermissions[$permission][] = $i;
  }
}
foreach($userPermissions as $permission => $values) {
  echo "{$permission} = " . implode(',', $values) . ":::";
}

答案 3 :(得分:0)

你可以这样做 - 基本上,在输出它们之前组合这些值。

$permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all");
foreach($permissions as $permission) {
  $vals = array();
  for ($i = 1; $i <= 5; $i++) {
    $mode = $_POST['permission'][$i][$permission];
    if($mode == 1) 
      $vals[] = $i;
  }
  if(count($vals))
    echo $permission . ' == ' . implode(',', $vals);
}