Pablo Malynovytch Pablo Malynovytch - 1 month ago 7
MySQL Question

Get MySql data an put into an multidimensional array

Can be PHP or Mysql solution...
I want to be able to store some data that has been selected from a mysql database in a php array. So far, I have only been able put in a "fake" array

$SQL = "SELECT * FROM continents RIGTH JOIN Country ON Country_Continents = continents_ID";
while ($CONT = mysql_fetch_array($DataSet)){
$array_cont[] = $CONT["continents_name"];
$country_ID_rry [] = $CONT;
}


Then I get an array per continent and i the continent array get the countries name..

Array
(
[0] => Array
(
[0] => America
[continents_name] => America
[1] => 3
[country_id] => 3
[2] => México
[country_name] => México
)

[1] => Array
(
[0] => SouthAmérica
[continents_name] => SouthAmerica
[1] => 2
[country_id] => 2
[2] => Argentina
[country_name] => Argentina
)

[2] => Array
(
[0] => SotuhAmerica
[continents_name] => SouthAmerica
[1] => 5
[country_id] => 5
[2] => Venezuela
[country_name] => Venezuela
)

[3] => Array
(
[0] => SouthAmerica
[continents_name] => SouthAmerica
[1] => 6
[country_id] => 6
[2] => Colombia
[country_name] => Colombia
)

[4] => Array
(
[0] => Caribe
[continents_name] => Caribe
[1] => 1
[country_id] => 1
[2] => Cuba
[country_name] => Cuba
)

)


but I want something like that...

Array
(
[SouthAmerica] => Array
(
[0] => Argentina
[1] => Brazil
[2] => Colombia
)

[NorthAmerica] => Array
(
[0] => Usa
[1] => Mexico
[2] => Canada
)

[Europa] => Array
(
[0] => Ukraine
[1] => Germany
[2] => England
)

)

Answer

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_array()
  • PDOStatement::fetch()

But the general idea (fetching just the associtive array):

while ($CONT = mysql_fetch_assoc($DataSet)){
    $Pais_ID_rry[$CONT["continents_name"]][] = $CONT['country_name'];
}

In addition, if you only want Continent and Country names:

SELECT continents_name, country_name FROM continents . . .