douque2016 2019-06-22 09:01
浏览 38
已采纳

关于sql选择和print_r数组的问题[重复]

This question already has an answer here:

I have a question, first look my code:

$testsql = $db->prepare('SELECT * FROM forum_sujets');
$testsql->execute();
$test = $testsql->fetch();
print_r($test);

My DB:

enter image description here

Ok, so I want to select my information in array, and i wan't this array look like:

array(              
    'id' => '1', array(
        'nom' => 'test',
        'titre' => 'test',
        'auteur' => 'test',
    ),
    'id' => '2', array(
        'nom' => 'test2',
        'titre' => 'test2',
        'auteur' => 'test2',
    ),
 );

Ok, and after my array look like this, I want to echo, for exemple, the name of the ID "2", I don't known if i'm clearful. I hope you can help me, see u :)

</div>
  • 写回答

1条回答 默认 最新

  • dtstnjl898781429 2019-06-22 09:32
    关注

    An example, your screenshot is not so good so I suppose you have colums titre, nom et auteur dans votre table:

    $testsql = $db->prepare('SELECT id, titre, nom, auteur FROM forum_sujets');
    $testsql->execute();
    $data = [];
    while ($test = $testsql->fetch()) {
        $id = $test['id'];
        $data[$id] = [
            'nom' => $test['nom'],
            'auteur' => $test['auteur'],
            'title' => $test['title'],
        ];
    }
    
    print_r($data);
    

    The output will be like :

    array(              
        1 => array(
            'nom' => 'test',
            'titre' => 'test',
            'auteur' => 'test',
        ),
        2 => array(
            'nom' => 'test2',
            'titre' => 'test2',
            'auteur' => 'test2',
        ),
     );
    

    As you cannot have two same key in one array

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?