Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php SQL-按关联值分隔结果?_Php_Mysql - Fatal编程技术网

Php SQL-按关联值分隔结果?

Php SQL-按关联值分隔结果?,php,mysql,Php,Mysql,在做任何事情之前,我先让你看看我的桌子: (在PHP的上下文中) 我想通过一个查询创建一个多维数组,这样一组具有相同id的标记将在相同的位置结束: <?php // Given the above example table, it would essentially produce this: $my_1 = array ( array('ect'), array('123', 'tag'),

在做任何事情之前,我先让你看看我的桌子:

(在PHP的上下文中)
我想通过一个查询创建一个多维数组,这样一组具有相同id的标记将在相同的位置结束:

<?php

  // Given the above example table, it would essentially produce this:

  $my_1 = array
            ( array('ect'),
              array('123', 'tag'),
              array('lolly', 'hat')
            );

使用二维数组:

$array = array();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $id = $row['id'];
    $tag = $row['tag'];
    if (isset($array[$id])) {
        $array[$id][] = $tag;
    } else {
        $array[$id] = array($tag);
    }
}
生成的
$array

array(1 => array('ect'),
      7 => array('123', 'tag'),
      9 => array('lolly', 'hat'))

不要使用单独的变量,使用二维数组。
<?php

  $array = array();
  foreach($tags as $tag)
  {
    if(array_key_exist($tag->id,$array)){
      //if key is assigned in array, we can push value to key
      $array[$tag->id] = array_push($tag->value,$array[$tag->id]);
    }else{
      //if key is not assigned we will create key and push value
      $array[$tag->id] = $tag->value;
    }
  }

  //usage

  print_r($array[7]); // list tags with id 7

?>