sql >> Database >  >> RDS >> Mysql

PHP, MySQL, SELECT-vraag

Ik denk dat de beste manier om dit te doen in de PHP-code zou zijn, in plaats van in SQL.

U kunt dit bereiken door eenvoudig een associatieve array in PHP te maken, met het veld "tekst" als sleutel, die de gewenste gegevens bevat - en deze in te vullen terwijl u informatie uit de database haalt.

Een voorbeeld:

SQL:SELECT * FROM myTable

PHP-code:

<?php

// Connect to MySQL database
$result = mysql_query($sql_query_noted_above);
$stringsInfo = array();
while ($row = mysql_fetch_assoc($result))
{
    if (!isset($stringsInfo[$row['text']]))
    {
        $stringsInfo[$row['text']] = array('types' => array(), 'idAccounts' => array());
    }

    $stringsInfo[$row['text']]['types'][] = $row['type'];
    $stringsInfo[$row['text']]['idAccounts'][] = $row['idAccount'];
}

?>

Dit geeft je een array als volgt:

'myTextString' => 'types' => 'type1', 'type2', 'type3'
                  'idAccounts' => 'account1', 'account2'

'anotherTextString' => 'types' => 'type2', 'type4'
                       'idAccounts' => 'account2', 'account3'

enzovoort.

Ik hoop dat het nuttig is.

EDIT:Poster vroeg om hulp bij weergave.

<?php

foreach ($stringsInfo as $string => $info)
{
    echo $string . '<br />';
    echo 'Types: ' . implode(', ', $info['types']); // This will echo each type separated by a comma
    echo '<br />';
    echo 'ID Accounts: ' . implode(', ', $info['idAccounts']);
}

/* Als alternatief kun je elke array in $info herhalen als je meer controle nodig hebt */

foreach ($stringsInfo as $string => $info)
{
    echo $string . '<br />';
    echo 'Types: ';
    foreach ($info['types'] as $type)
    {
        echo $type . ' - ';
    }
    echo '<br />';
    echo 'ID Accounts: '
    foreach ($info['idAccounts'] as $idAccount)
    {
        echo $idAccount . ' - ';
    }
}


  1. Hoe maak je een geneste tabel als database-object in Oracle?

  2. MySQL:UNIEK, maar STANDAARD NULL - toegestaan ​​door het maken van een tabel. Er mag meer dan 1 NULL worden ingevoegd. Waarom?

  3. C# met MySQL INSERT-parameters

  4. Upgrade rijen alleen bij app-upgrade