Pavle Pavlovic
Pavle Pavlovic

Reputation: 17

How to add array in multidimensional array in PHP from mysql database?

This is my php code, I'm fetching data from mysql database:

    $result2 = $mysqli->query("SELECT * FROM movies");
    $lista = array();
    while ($row2 = $result2->fetch_array())
    {
        $ime=$row2['Title'];
        $result1 = $mysqli->query("SELECT AVG(Rating) FROM ratings WHERE Title='$ime'");
        while ($row1 = $result1->fetch_array()){

            $lista = array
            (
                array($row2['Title'],round($row1['AVG(Rating)'],1),$row2['Year'])
            );
        }
    }
    var_dump($lista);

I get this result:

array (size=1)
  0 => 
    array (size=3)
      0 => string 'Memento' (length=7)
      1 => float 8.5
      2 => string '2000' (length=4)

I think that the problem is that every new array is overwriting last one, and i get only size=1 array. So, how to add array into array and not overwrite it?

I want my array to look like this:

array (size=4)
  0 => 
    array (size=3)
      0 => string 'Forrest Gump' (length=12)
      1 => float 4.5
      2 => string '1994' (length=4)
  1 => 
    array (size=3)
      0 => string 'The Prestige' (length=12)
      1 => float 7
      2 => string '2006' (length=4)
  2 => 
    array (size=3)
      0 => string 'The Usual Suspects' (length=18)
      1 => float 7.5
      2 => string '1995' (length=4)
  3 => 
    array (size=3)
      0 => string 'Memento' (length=7)
      1 => float 8.5
      2 => string '2000' (length=4)

Upvotes: 1

Views: 68

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

You should do something like this:

$result2 = $mysqli->query("SELECT * FROM movies");
$lista = array();
while ($row2 = $result2->fetch_array())
{
    $ime=$row2['Title'];
    $result1 = $mysqli->query("SELECT AVG(Rating) FROM ratings WHERE Title='$ime'");
    while ($row1 = $result1->fetch_array()){

        $lista[] = array($row2['Title'],round($row1['AVG(Rating)'],1),$row2['Year']);
    }
}
var_dump($lista);

Upvotes: 1

Related Questions