array structure of database results

前端 未结 2 1348
终归单人心
终归单人心 2021-01-26 15:17

This might be quite a trivial question, but which of these methods is best practice for structuring an array for return db results? say a list of blog posts... Sorting and group

2条回答
  •  北海茫月
    2021-01-26 16:07

    The second is better AND simpler to set up:

    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        $posts[] = $row;
    }
    
    // total number of posts
    $nrPosts = count($post);
    

    This will auto-index the array numerically, and you don't need to copy anything from $row into $post, it'll simply copy the whole row.

    The second structure is better:

    • It logically groups the data of a post into a structure
    • It requires no handling of the data, more than the initial filling of the $post-array
    • You can easily handle any number of blog posts with a single index / range of indexes

提交回复
热议问题