2015-11-22 69 views
1

我試圖從MySQL查詢中構建一個句子。我相信我有連接部分工作,因爲我已經替換了一個靜態數組。任何人都可以引導我以正確的方向來看看我的while循環看起來會產生所需的數組?我如何從我的mysql語句創建一個關聯數組?PHP準備語句concatenate:while循環中的「逗號」,「和」和「句點」

$query = "SELECT name, dob FROM children WHERE personal_id = ?"; 
$statement = $db->prepare($query); 
$statement->bind_param('i', $_SESSION['mysqlID']); 
$statement->bind_result($name, $dob); 
$statement->execute(); 

// Store the results 
$statement->store_result(); 

// Get the number of rows 
$num_of_rows = $statement->num_rows; 


**//I believe my problem lies in this array ?** 
$m_children = []; 
while ($statement->fetch()) { 
    $m_children[] = $name; 
    $m_children[] .= $dob; 
} 

$num_children = intval($num_of_rows); 
$children = []; 

foreach ($m_children as $k => $v) { 
    $dob = strtotime($dob[$k]); 
    $children[] = "$v, born on {$dob}"; 
} 

$tmp = array_pop($children); 

    if ($num_children > 1) { 
    $children_type = 'children'; 
    $children = join(', ', $children) . ' and ' . $tmp; 
    } else { 
    $children_type = 'child'; 
    $children = $tmp; 
    } 

$children = "<p>I have the following ". $children_type .": ". $children .".</p>"; 
+0

如何從我的mysql語句創建關聯數組? – user1040259

+0

期望的輸出示例? –

+0

謝謝。數據庫正在返回姓名和出生日期。我需要讀這個句子。 '姓'出生於'約會','姓'出生於'約會','姓'出生於'約會'。如果一個結果只是以一段時間結束。 – user1040259

回答

3

總的來說你的代碼看起來不錯。語法部分肯定是固定的(彈出最後一個元素,用逗號等加入其餘元素...)

如您懷疑,您的問題代碼是您標記的那部分。

//I believe my problem lies in this array ? 
$m_children = []; 
while ($statement2->fetch()) { 
    $m_children[] = $name; 
    $m_children[] .= $dob; 
} 

$num_children = intval($num_of_rows); 
$children = []; 

foreach ($m_children as $k => $v) { 
    $dob = strtotime($dob[$k]); 
    $children[] = "$v, born on {$dob}"; 
} 

這裏有一個建議改進:

$children = []; 
while($statement2->fetch()) { 
    $children[] = $name." born on ".date("d/M/Y",strtotime($dob)); 
} 
$num_children = count($children); 

有沒有必要做對數據兩遍,你將需要格式化了出生日期(否則你只是得到一個時間戳)。這段代碼可以繼續到你的語法格式,這對我來說似乎很好。

+0

謝謝你在這裏的指導,做到了! – user1040259