bikey77
bikey77

Reputation: 6672

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.

Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)

I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.

How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc? PS:I know, is complicated but I cant come up with a better idea right now.

Upvotes: 2

Views: 14088

Answers (3)

Derk Arts
Derk Arts

Reputation: 3460

My solution for how I understand you question:

// Make a MySQL Connection

$sQuery = "SELECT f1,f2,... FROM table WHERE id = ..."; 

$oResult = mysql_query($sQuery) or die(mysql_error());

//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);

//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());

//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
    $aExplodedCol = explode("#",$sColVal);
    //The code below could be nicer when turned into a looped that looped over every language,
    //But that would make the code less readable
    $aProductProperties['English'][$sColName]  = $aExplodedCol[0];
    $aProductProperties['French'][$sColName]  = $aExplodedCol[1];
    $aProductProperties['Dutch'][$sColName]  = $aExplodedCol[2];

}

//Done, you should now have an array with all the product properties in every language

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

Not sure this is the best way togo but you could define an array with your langs, then access the result by lang

<?php 
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);


while ($row=mysql_fetch_assoc($result)) {
    $specs=explode('#',$row['f1']);
    $other=explode('#',$row['f2']);
    ...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';

echo $specs[$langs[$lang]];

?>

Upvotes: 0

swatkins
swatkins

Reputation: 13640

Try this:

$result = mysql_query("...");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $arr = array();
    foreach ($row as $k=>$v)
    {
        $features = explode("#", $v);
        $value = $features[1]; // get the specific language feature
        $arr[] = $value;
    }
    $specs = join(", " , $arr);
}

Upvotes: 7

Related Questions