按ID分组值

时间:2012-01-08 22:59:28

标签: php sql arrays

我有这段代码:

 function get_posts_tags($db, $start, $number_of_posts) {
    //query
    ");

    $sql -> bind_param('ii',$start, $number_of_posts);
    $sql -> execute();
    $sql -> bind_result($id_offer, $tag);

    $posts_tags = array();
    while ($sql -> fetch()) {
        $posts_tags[] = array('id_offer'=>$id_offer, 'tag'=>$tag);
    };

    $sql->close();

    var_dump($posts_tags);
}

输出:

array
  0 => 
    array
      'id_offer' => int 77
      'tag' => string 'PHP' (length=3)
  1 => 
    array
      'id_offer' => int 77
      'tag' => string 'JAVA' (length=4)
  2 => 
    array
      'id_offer' => int 76
      'tag' => string 'PHP' (length=3)
  3 => 
    array
      'id_offer' => int 76
      'tag' => string 'JAVA' (length=4)

我想要的是按照数组$posts_tags[]中的id对标签进行分组。我怎样才能做到这一点 ?目前,我所拥有的是DB的简单输出。

类似的东西:

 array
      0 => 
        array
          'id_offer' => int 77
          'tag0' => string 'PHP' (length=3)
          'tag1' => string 'JAVA' (length=4)
      1 => 
        array
          'id_offer' => int 76
          'tag0' => string 'PHP' (length=3)
          'tag1' => string 'JAVA' (length=4)

...

由于

1 个答案:

答案 0 :(得分:1)

这样的事情对你有用吗?

array
    0 => 
        array
            'id_offer' => int 77
            'tags'     => array
                0 => string 'PHP' (length=3)
                1 => string 'JAVA' (length=4)
    1 => 
        array
            'id_offer' => int 76
            'tags'     => array
                0 => string 'PHP' (length=3)
                1 => string 'JAVA' (length=4)

这可以这样完成:

while ($sql -> fetch()) {
    $post_tags[$id_offer]['id_offer'] = $id_offer;
    $post_tags[$id_offer]['tags'][]   = $tag;
};

// Reset the array keys with array_values() or array_merge()
$post_tags = array_values($post_tags);