2012-10-16 67 views
0

我有一個小任務,其中有一個mysql表「stores」。它包含一個「categories」列。每個類別的字段都包含不同的值,比如「22,44,33,55,24,33,22」 現在從該字段獲取每個值,我需要從另一個表中的「父」列中獲取值。 (與ID鏈接)我選擇整個字符串,但我想選擇每個數字。請幫我解決一下這個。爆炸並選擇數組中的每個元素

$db_selected = mysql_select_db("",$con); 
$sql = "SELECT categories from shops"; 
$array = mysql_query($sql,$con); 
while($row=mysql_fetch_array($array)){ 
foreach($row as $value){ 
    $result= explode(" ", $value); 
    foreach($result as $newvalue){ 
    $query="SELECT parent FROM categories where categories.id=$newvalue<br/>"; 
    echo $query; 
    } 
    } 
    } 
mysql_close($con); 
?> 
+3

這就是爲什麼你有一個單獨的'shops_categories'表正常化您的數據庫,記錄這種關係,而不是堆砌逗號分隔的數字成相同的字段。 – deceze

+0

對不起,我不能正常化我的數據庫,但需要一個解決方案... – user1694724

+0

檢查MySQL函數['find_in_set'](http://dev.mysql.com/doc/refman/5.0/en/string-functions。 html#function_find-in-set) – air4x

回答

1

您正在根據空間特徵進行爆炸,但您的價值需要根據,進行爆炸。所以嘗試

$result= explode(",", $value); 
foreach($result as $newvalue){ 

    $query="SELECT parent FROM categories where categories.id='$newvalue'"; 
                  //^Quotes the Value 
                  // Remove the <br /> 

    echo $query."<br />"; //Instead add it here and avoid the bug if you decide the run the query 

    // This example is showing mysql_* library but it is deprecated 

    $result = mysql_query($query); 
    $row = mysql_fetch_assoc($result); 
    $parent = $row['parent']; //Now you can something like this 


} 
+0

謝謝,我怎樣才能打印父母的價值? – user1694724

+0

@ user1694724,增加了一個例子 – Starx

+0

mysql_fetch_assoc()期望參數1是資源,給定的布爾值......出現錯誤 – user1694724

0

如果您的類別列中包含「22,44,33,55,24,33,22」那麼可以肯定你的爆炸應該是

$result= explode(",", $value); 

如發生爆炸逗號字符串中給你22,44,33 ...

+0

謝謝,我怎樣才能打印父母的價值? – user1694724

+0

如果您使用我們所有人建議的更改更新了您的代碼,您應該看到它會按照您的要求打印出您的查詢。 – BugFinder

0

我認爲這個問題是在這裏$result= explode(" ", $value); 應該$result= explode(",", $value);

+0

謝謝,我如何打印父項的值? – user1694724

+0

使用從$ result提取的值進行另一個查詢。 – Amirshk

0
$result= explode(",", $value); 

由於字符串的格式是用逗號分隔的,因此應該用逗號代替字符串進行爆炸。

+0

謝謝,我怎樣才能打印父母的價值? – user1694724

0

是否用逗號分隔值?

即使你的問題是一個數據庫設計,explode(',', $value)應該讓你的ID。

+0

謝謝,我怎樣才能打印父母的價值? – user1694724

+0

那麼,你已經有了與該類別相關的類別id,並且該id可以查詢同一個表,但正如我所說的,更好的表格設計必須是更好的方法。 –