Hello. I have a two-dimensional array:

$massiv = array ( 'КАТЕГОРИЯ: Материал' => array ( 0 => 'Дерево', 1 => 'Сталь', ), 'КАТЕГОРИЯ: Применение' => array ( 0 => 'В сухом помещении', 1 => 'Сауны', ), ); 

I want to make sure that all these values ​​for the array are taken from the MySQL database, since there may be an unspecified number of parameters, and it’s not very convenient to write everything into the code.

That is, categories and sub categories can be any number.

Categories are stored in the category table, and subcategories in the podcat table.

Here's how to bring them into a similar array, I have not yet come to the conclusion ...

I would be grateful for any useful information.

  • one
    How are they stored in the database and how is the connection with category indicated in podcat? - Yaroslav Molchan
  • @YaroslavMolchan in the podcat table is the id_cat cell - it has a numeric value that corresponds to the id entry in the category table - iKey

1 answer 1

Change the request to your own if I did not guess somewhere, but this code should output what you need:

 $sql = 'SELECT `podcat`.`name` as `prodName`, `category`.`name` as `catName` FROM `podcat` INNER JOIN `category` WHERE podcat.id_cat = category.id;'; $res = $db->query($sql); $result = []; while($podcat = $res->fetch(PDO::FETCH_ASSOC)) { $result[$podcat['catName']][] = $podcat['prodName']; } var_dump($result); 

UPD. Here is an option without PDO:

 $sql = 'SELECT `podcat`.`name` as `prodName`, `category`.`name` as `catName` FROM `podcat` INNER JOIN `category` WHERE podcat.id_cat = category.id;'; $res = mysql_query($query); $result = []; while ($podcat = mysql_fetch_assoc($res)) { $result[$podcat['catName']][] = $podcat['prodName']; } var_dump($result); 
  • and not to do without PDO? I have mysql - ikeyey
  • I only get CATEGORY, and instead of subcategories, I get exactly the same categories as there should be subcategories - iKey
  • it turns out a type: CATEGORY (category, category, category). but you need CATEGORY (subcategory, subcategory, subcategory) - iKey
  • Try to make podcat . name as podName by analogy with catName and also in while replace, and better show what happens, because it should work out correctly - Yaroslav Molchan
  • Yaroslav Molchan If you read my comment link in question, you could see there that PDO can do the necessary array itself, without using a loop, which is much shorter and more efficient. - Mike