July 12, 2010

Make a multidimensional array through loop!

Question by esafwan

How can i make an array like below through a loop? The text will generated from database!

 $listofimages = array(
        array(  'titre' => 'PHP',
                'texte' => 'PHP (sigle de PHP: Hypertext Preprocessor), est un langage de scripts (...)',
                'image' => './images/php.gif'
        ),
        array(  'titre' => 'MySQL',
                'texte' => 'MySQL est un système de gestion de base de données (SGDB). Selon le (...)',
                'image' => './images/mysql.gif'
        ),
        array(  'titre' => 'Apache',
                'texte' => 'Apache HTTP Server, souvent appelé Apache, est un logiciel de serveur (...)',
                'image' => './images/apache.gif'
        )
    );

Answer by hsz

Something like :

$listofimages = array();

foreach ( $rowset as $row ) {

    $listofimages[] = array(
        'titre' => $row['titre'],
        'texte' => $row['texte'],
        'image' => $row['image']
    );

}

?

Answer by Starx

do something like this,

$result = mysql_query("SELECT * FROM table;");
while($row = mysql_fetch_assoc($result) {
    //$row will hold all the fields's value in an array
    $mymainarray[] = $row; //hold your array into another array
}

//To display
echo "<pre>";
print_r($mymainarray);
echo "</pre>";

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!