Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

php - Extract all value from table product option with a loop or array

I have a simple marketplace. I have table product and table product_option

| id | codice_prodotto  | attributo_chiave  | valore_chiave |
| 1  | 001              | colore            | rosso         |
| 2  | 001              | taglia            | m             |
| 3  | 002              | taglia            | s             |

now I want to select all attributes and values for the product 001 So I have my query in php

$query = "SELECT * from table WHERE codice_prodotto = '001'";

now I want to loop this and extract the key and value

colore = rosso
taglia = m

how can I do this? Whit a while loop is not the right way

while ($riga_risultato = $eseguo_query_prodotto->fetch_assoc()) {

//    print_r($riga_risultato);
echo $riga_risultato['attributo_chiave'];

}

the output is (right)

tagliacolore

but I want to have attribute and value for this product in different variable, so if I have more records there is no problem. Can you help me? Maybe I have to transform the array from the query select? thanks


Hi, maybe this could be a solution or there is other simple way?

// query
$query_prodotto = "SELECT * from prodotto_opzioni WHERE codice_prodotto = '001'";
$eseguo_query_prodotto = $connessione->query($query_prodotto) or die ("errore query". $connessione->error);

//estraggo i valori
while ($riga_risultato = $eseguo_query_prodotto->fetch_assoc()) {

    // populate multidimensional array with all values I want
    $js_arr[] = [
        'attributo_chiave' => $riga_risultato['attributo_chiave'],
        'valore_chiave' => $riga_risultato['valore_chiave']
        
    ];
}

//extract array
foreach ($js_arr as $pette){
    echo  $pette['attributo_chiave'].'='.$pette['valore_chiave'].'<br>';

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your table is basically a denormalized key value store. One option here would be to use a pivot query with aggregation to turn out specific keys and values, e.g.

SELECT
    codice_prodotto,
    MAX(CASE WHEN attributo_chiave = 'colore' THEN valore_chiave END) AS colore,
    MAX(CASE WHEN attributo_chiave = 'taglia' THEN valore_chiave END) AS taglia,
    ...   -- other keys here
FROM yourTable
WHERE
    codice_prodotto = '001'
GROUP BY
    codice_prodotto;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...